JLabel不会显示图像

Rip*_*pIt 5 java swing jlabel jbutton

我正在使用 Java 创建一个 Tic-Tac-Toe 游戏。现在,我有了它,因此当您单击一个按钮时,该按钮JButton将从 中删除JPanelJLabel添加一个包含 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();
}
}
Run Code Online (Sandbox Code Playgroud)

问题图片

Dav*_*amp 3

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

        p11.revalidate();
        p11.repaint();
Run Code Online (Sandbox Code Playgroud)

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

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

  • 如果您还解释了为什么这种方法可能有效,这可能会很有用。 (2认同)