我正在编写一个ticTacToe游戏。为此,我创建了JButton并将它们存储到数组中。当用户点击该特定按钮时,我想知道哪个按钮被点击。我试图找到哪些JButton被点击在“按钮”数组中以设置该特定按钮的文本。获取JButton数组中元素的索引。 Java
public class tester extends JFrame{
boolean crossed = false;
JButton[] buttons = new JButton[9];
public tester(){
super("The title");
this.setLayout(new GridLayout(3,2));
for(int x = 0 ; x < buttons.length; x++){
buttons[x] = new JButton();
this.add(buttons[x]);
buttons[x].addActionListener(new tickSquare());
}
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setSize(400, 400);
this.setVisible(true);
}
public class tickSquare implements ActionListener{
public void actionPerformed(ActionEvent e){
}
}
public static void main(String[] args){
new tester();
}
}
[ActionEvent的JAVADOC]应该工作(https://docs.oracle.com/javase/7/docs /api/java/awt/event/ActionEvent.html)。如果您返回继承链,您可以简单地使用[EventObject#getSource](https://docs.oracle.com/javase/7/docs/api/java/util/EventObject.html#getSource())以便获取已被点击并引发事件的实例。实际上不需要获取任何索引或其他东西,你可以简单地使用这个方法来获得正确的点击JButton实例并继续。 – SomeJavaGuy
既然你调用'addActionListener(new tickSquare())'反正你也可以传递一些信息给侦听器的构造函数。与该按钮关联的正方形。除此之外,你应该考虑你的类名以及为什么它们应该遵守[Java命名约定](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367)。 – Thomas