我正在使用 Java 创建一个井字游戏。现在,我有它,所以当您单击一个按钮时,该按钮JButton
将从 中删除,将添加JPanel
一个JLabel
包含 X 或 O 图像的按钮,然后JPanel
重新绘制 。但是,当我单击按钮时,图像不会显示,但按钮会消失。
创建按钮和JLabel
/ Image
:
package tictactoe;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.ImageIcon;
public class TicTacToe implements ActionListener
{
private JFrame holder = new JFrame();
private GridLayout layout = new GridLayout(3,3);
private FlowLayout panel = new FlowLayout(FlowLayout.CENTER);
private JPanel p11, p12, p13, p21, p22, p23, p31, p32, p33;
private JButton b1, b2, b3, b4, b5, b6, b7, b8, b9;
private ImageIcon iconX = new ImageIcon("iconX.png");
private JLabel xLabel = new JLabel(iconX);
private ImageIcon iconO = new ImageIcon("iconO.png");
private JLabel oLabel = new JLabel(iconO);
private int turn;
private char s1, s2, s3, s4, s5, s6, s7, s8, s9;
public TicTacToe()
{
paint();
}
private void paint()
{
holder.setLayout(layout);
holder.setSize(300,300);
b1 = new JButton("1");
p11 = new JPanel();
p11.setLayout(panel);
p11.add(b1);
holder.add(p11);
//Same block of code for the next 8 buttons/panels inserted here
holder.setVisible(true);
b1.addActionListener(this);
//Other action listeners inserted here
}
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == b1)
{
++turn;
p11.remove(b1);
if (turn % 2 == 1) { s1 = 'x'; p11.add(xLabel); }
else if (turn % 2 == 0) { s1 = 'o'; p11.add(oLabel); }
p11.repaint();
}
//Other action events inserted here
}
public static void main(String[] args)
{
TicTacToe game = new TicTacToe();
}
}