2017-04-11 47 views
0

我正在编写一个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(); 
    } 
} 
+0

[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

+0

既然你调用'addActionListener(new tickSquare())'反正你也可以传递一些信息给侦听器的构造函数。与该按钮关联的正方形。除此之外,你应该考虑你的类名以及为什么它们应该遵守[Java命名约定](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367)。 – Thomas

回答

0

将按钮编号从循环指定到它们的单击事件类。

for(int x = 0 ; x < buttons.length; x++) 
{ 
     buttons[x] = new JButton(); 
     this.add(buttons[x]); 
     buttons[x].addActionListener(new tickSquare(x)); 
} 

public class tickSquare implements ActionListener 
{ 
    public int ButtonNumber; 
    public tickSquare(int x) 
    { 
     ButtonNumber = x; 
    } 
    public void actionPerformed(ActionEvent e) 
    { 
     //do something with the button number 
    } 
} 

编辑:你应该做的按钮号码整数私人/保护,并添加get方法。

+0

感谢@SomeJavaGuy'对(INT I = 0; I

+0

@AzamatAdylbekov的更小,更流畅的版本可能是'((JButton的)e.getSource())的setText( “X”)';)你鸵鸟政策如果'e.getSource'已经提供给你,需要在数组中找到确切的'JButton'实例。在这一点上,你“只是”必须将它解析为一个“JButton”。 – SomeJavaGuy

0

,如果你把这个在ActionListener的 不太清楚,如果一切都写对

for(int i=0;i<buttons.length;i++){ 
if(e.getSource()==buttons[i]){ 
buttons[i].setText("x"); 
} 
} 
相关问题