4

我正在使用 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();
}
}

问题图片

4

2 回答 2

3

尝试在您的 s 实例上调用revalidate();then ,如下所示:repaint();JPanel

        p11.revalidate();
        p11.repaint();

Component添加或删除 a 时,有必要调用revalidate()此调用是一条指令,告诉 aLayoutManager根据新Component列表进行重置。revalidate()将触发repaint()对组件认为是“脏区”的调用。显然,并非您的所有区域JPanel都被RepaintManager.

repaint()用于告诉组件重新绘制自己。通常情况下,您需要调用它来清理像您这样的条件。

于 2012-08-02T18:55:48.397 回答
1
@Override
public void actionPerformed(final ActionEvent e)
{
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            if (e.getSource() == b1) {
                ++turn;
                p11.remove(b1);
                if (turn % 2 == 1) { s1 = 'x'; p11.add(new JLabel(iconX)); }
                else { s1 = 'o'; p11.add(new JLabel(iconO)); }
                //p11.revalidate();
                //p11.repaint();
            }
            **Other action events inserted here
        }
    });
}

invokeLater构造的语法有点多,但让事件处理线程处理按钮单击,然后进行更改。否则,您不能依赖立即重新绘制,并且 gui 的响应速度会降低。(Runnable 对象只能从外部访问final变量,即:不再分配的变量。)

组件之类JLabel的父组件有一个字段。因此,不能重用一个组件。因此new JLabel().

关于重新粉刷;总是先尝试它而不自己触发它。

于 2012-08-02T19:07:07.017 回答