我正在製作一個統計程序來練習我在Java中的GUI技能。將JButton放在堆棧上
我有一個程序,通過按下他們的名字打一個JButton來記錄籃球運動員的統計數據。然後它將統計數據添加到運行總數並更新記分牌。
我已經到了創建撤消按鈕的時候了。
因此,每次執行操作時,我都會將源按鈕添加到一堆JButton中。還有一些涉及鑄造,所以像這樣結束:
JButton source = (JButton) e.getSource();
theStack.push(source);
後來,在actionPerformed
方法我試圖通過撤銷函數來調用:
if(source.getText().equals("Undo")){
System.out.println("Undo");
JButton last = this.theStack.pop();
System.out.println(last.getText()); //Works fine.
System.out.println(last.getName()); //Produces a null value.
int player = Integer.parseInt(last.getName().trim());
undo(player, last.getText(), activePlayers);
}
爲什麼我收到了一個空名稱。 Eclipse在嘗試將名稱轉換爲int
時發生異常,因爲它正在轉換空值。我在actionPerformed
的其他部分使用.getName()
,但不是在這裏?
我的名字設置代碼,在for循環中做了很多次。
output[i][j] = new JButton("Make Two Points");
output[i][j].setName(i + "");
問題是最簡單的形式。
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
ArrayList<Integer> activePlayers = new ArrayList<Integer>();
activePlayers.add(player0Select.getSelectedIndex());
activePlayers.add(player1Select.getSelectedIndex());
activePlayers.add(player2Select.getSelectedIndex());
activePlayers.add(player3Select.getSelectedIndex());
activePlayers.add(player4Select.getSelectedIndex());
JButton source = (JButton) e.getSource();
theStack.push(source);
if(source.getText().equals("Make Two Points")){
this.makeTwoPoints(source.getName(), activePlayers); //source.getName() works here.
System.out.println("Two Points");
}
if(source.getText().equals("Undo")){
System.out.println("Undo");
JButton last = this.theStack.pop();
System.out.println(last.getText());
System.out.println(last.getName()); //last.getName() produces null here.
int player = Integer.parseInt(last.getName().trim());
undo(player, last.getText(), activePlayers);
}
}
當我生成它們時,我確實設置了它們,該名稱對應於列號,它將其轉換爲我的程序中的活動播放器。 –
@TrevorHutto:JVM正在告訴你,否則我相信JVM。請顯示您的設置代碼。 –
@TrevorHutto:您需要創建併發布可測試[mcve](http://stackoverflow.com/help/mcve),以便我們能夠充分理解您的問題。 –