【发布时间】:2014-03-04 07:03:10
【问题描述】:
我正在制作一个统计数据保存程序来练习我在 Java 中的 GUI 技能。
我有一个程序可以通过点击篮球运动员姓名下的 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);
}
}
【问题讨论】:
标签: java null stack jbutton undo