有关单击时更改按钮的Java ActionListeners

时间:2016-03-24 19:04:39

标签: java netbeans

package tictactoe;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TicTacToe extends JFrame implements ActionListener  {
    JPanel mainPanel=new JPanel();
    JButton[] buttons=new JButton[9];
public TicTacToe()
{
    super("Tic Tca Toe");
    setSize(400,400);
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLookAndFeel();
    mainPanel.setLayout(new GridLayout(3,3,5,5));
       for(int i=0;i<9;i++)
       {
           buttons[i]=new JButton();
           buttons[i].addActionListener(this);
           mainPanel.add(buttons[i]);
       }

        add(mainPanel);
        setVisible(true);
}
    private void setLookAndFeel()
    {
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        }catch(Exception e)
        {

        }
    }

public void actionPerformed(ActionEvent event) 
{


}
public static void main(String[] args)
{
new TicTacToe();
}

}

问题是我想让它成为当我们点击里面的按钮时,他们点击了从空白到X到O的变化里面的文字为空白如果你继续点击这样它循环通过这3个状态但是我无法找到任何帮助吗?

1 个答案:

答案 0 :(得分:1)

您可以使用if-else语句来完成。

public class TicTacToe extends JFrame implements ActionListener {

    public static final String X = "X";
    public static final String O = "O";

    .
    .
    .

    public void actionPerformed(ActionEvent event) {
        JButton button = (JButton) event.getSource();

        if (button.getText().isEmpty()) {
            button.setText(X);
        } else if (button.getText().equals(X)) {
            button.setText(O);
        } else {
            button.setText("");
        }
    }
}