如何制作一个没有点击的按钮?

时间:2017-03-16 19:26:37

标签: java image swing user-interface

我正在制作一个tic tac toe游戏,如何让按钮只是某个字母。单击按钮时,它会转到x但是再次按下它会转到o。如何制作它以使其固定而不是在按下后再制作?

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class TicTacToeSample extends JFrame implements ActionListener
{
    private JFrame game = new JFrame("TicTacToe");
    private JButton button1 = new JButton("");
    private JButton button2 = new JButton("");
    private JButton button3 = new JButton("");
    private JButton button4 = new JButton("");
    private JButton button5 = new JButton("");              
    private JButton button6 = new JButton("");
    private JButton button7 = new JButton("");
    private JButton button8 = new JButton("");
    private JButton button9 = new JButton("");  
    private String letter = "X";
    private int count = 0;
    private boolean win = false;

    public TicTacToeSample()
    {
        game.setSize(300,300);
        game.setDefaultCloseOperation(EXIT_ON_CLOSE);
        game.setLayout(new GridLayout(3, 3));

        game.add(button1);
        game.add(button2);
        game.add(button3);
        game.add(button4);
        game.add(button5);
        game.add(button6);
        game.add(button7);
        game.add(button8);
        game.add(button9);


        button1.addActionListener(this);
        button2.addActionListener(this);
        button3.addActionListener(this);
        button4.addActionListener(this);
        button5.addActionListener(this);
        button6.addActionListener(this);
        button7.addActionListener(this);
        button8.addActionListener(this);
        button9.addActionListener(this);

        game.setVisible(true);
    }


        public void actionPerformed(ActionEvent event) 
        {
            count++;

            if (count == 1 || count == 3 || count == 5 || count == 7 || count == 1)
            {
                letter = "X";
            }
            else if (count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
            {
                letter = "O";
            }

            if(event.getSource()== button1)
            {
            button1.setText(letter);
            }
            if(event.getSource()== button2)
            {
            button2.setText(letter);
            }
        }




      public static void main(String[] paramArrayOfString)
      {
        TicTacToeSample board = new TicTacToeSample();
      }
}

1 个答案:

答案 0 :(得分:2)

在ActionListener中,通过调用ActionEvent参数上的getSource()来获取按下的按钮。通过调用getText()来查看其文本,如果有的话。如果有文字,请不要更改。简单。