2017-04-11 37 views
0

私は三目並べゲームをコーディングしています。そのために私は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を]書かれている場合はかなり確実ではないのactionListener でこれを入れた場合、それが動作するはずです(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(新tickSquare())を呼び出しているのでそのボタンに関連付けられた四角形それ以外にも、クラス名と、[Java命名規則](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367)に従うべき理由について考える必要があります。以下のための '@SomeJavaGuy – 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

おかげでは、(i = 0、int型、iがbuttons.lengthを<; Iは++){ \t \t \t \t(e.getSource()==ボタン[I]){ \t \t \t \t \tボタン[I場合] .setText( "X"); \t \t \t \t} \t \t \t} 'これは –

+0

@AzamatAdylbekovを働い小さく、よりスムーズなバージョンは'((JButtonの)e.getSource())のsetText( "X")可能性があり、 ';。。)あなたはドント'e.getSource'がすでにあなたにそれを配送している場合は、配列内の正確な' JButton'インスタンスを見つける必要があります。この時点で、単に「JButton」として解析する必要があります。 – SomeJavaGuy

0

すべてが右

for(int i=0;i<buttons.length;i++){ 
if(e.getSource()==buttons[i]){ 
buttons[i].setText("x"); 
} 
} 
関連する問題