2017-08-30 6 views
0

これはJavaを使用したtictactoeゲームを作成するための第一歩です。ボタン1をクリックしても数字1を出力したいが動作しない

ボタンをクリックしたときに数字1を出力したいと思います。ボタンが9個ありますが、何が問題なのですか?e.getsourceの方法とB1ボタンは同じではありません。なぜこうなった?

package tictactoe; 

import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class TicTacToe implements ActionListener{ 

JFrame frame1; 
JButton B1 = new JButton(); 
JButton B2 = new JButton(); 
JButton B3 = new JButton(); 
JButton B4 = new JButton(); 
JButton B5 = new JButton(); 
JButton B6 = new JButton(); 
JButton B7 = new JButton(); 
JButton B8 = new JButton(); 
JButton B9 = new JButton(); 

public void createGui(){ 
    frame1 = new JFrame(); 
    frame1.setTitle("TicTacToe"); 
    frame1.setSize(600, 600); 
    frame1.setLayout(new GridLayout(3,3,0,0)); 
    frame1.setLocationRelativeTo(null); 

    frame1.add(B1); 
    frame1.add(B2); 
    frame1.add(B3); 
    frame1.add(B4); 
    frame1.add(B5); 
    frame1.add(B6); 
    frame1.add(B7); 
    frame1.add(B8); 
    frame1.add(B9); 

    TicTacToe A1 = new TicTacToe(); 

    B1.addActionListener(A1); 
    B2.addActionListener(A1); 
    B3.addActionListener(A1); 
    B4.addActionListener(A1); 
    B5.addActionListener(A1); 
    B6.addActionListener(A1); 
    B7.addActionListener(A1); 
    B8.addActionListener(A1); 
    B9.addActionListener(A1); 

    // frame1.pack(); 
    frame1.setVisible(true); 
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} 

public void actionPerformed(ActionEvent e) { 
    if(e.getSource()==B1){ 
     B1.setText("1"); 
    } 
} 

public static void main(String[] args) { 
    TicTacToe T1 = new TicTacToe(); 
    T1.createGui(); 
} 
} 
+1

Javaネーミングコンバージョンを処理します。変数名は小文字で始まる必要があります – Jens

答えて

2

あなたのプログラムが動作しない理由は、あなたがJButton.addActionListener()へのパラメータとして使用し、新たな三目並べを作成することです。代わりにthisを使用して、A1を削除してください。

B2.addActionListener(this); 

次に動作します。

しかし、私はJButton.addActionListener()を使用するよりも別のアプローチを提案しています。

ActionをパラメータとするJButtonコンストラクタを使用できます。 AbstractActionに拡張されたActionを実装し、実装する必要があるactionPerformed()メソッドのテキストを設定します。 Actionに、押されたときに書き込むテキストのパラメータを使用させることができます。

private class PressedAction extends AbstractAction { 
    private final String text; 

    public PressedAction(String text) { 
     this.text = text; 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     ((JButton) e.getSource()).setText(text); 
    } 
} 
関連する問題