繁体   English   中英

我想在单击按钮1时打印数字1,但它不起作用

[英]I want to print number 1 when click the button 1 but it doesn't work

这是使用Java制作ticticactoe游戏的第一步。

我想在单击按钮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();
}
}

您的程序不起作用的原因是,您创建了一个新的TicTacToe,用作JButton.addActionListener()参数。 尝试使用this代替并删除A1

B2.addActionListener(this);

然后它将起作用。

但是我建议使用JButton.addActionListener()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM