2017-08-30 38 views
0

这是使用Java制作tictactoe游戏的第一步。我想单击按钮1打印编号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命名converntion。变量名称应该以小写字符开头 – Jens

回答

2

的理由让你的程序不起作用是您创建作为参数传递给JButton.addActionListener()使用新的井字游戏。尝试使用this,并删除A1

B2.addActionListener(this); 

然后它会工作。

但是我有一个不同的方法比使用JButton.addActionListener()建议。

相反,您可以使用以Action作为参数的构造函数JButton。实施您自己的Action,它扩展了AbstractAction,然后在需要实施的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); 
    } 
} 
相关问题