简体   繁体   English

带按钮的 Swing JPanel 无法重新绘制

[英]Swing JPanel With Buttons Cannot Repaint

I am currently building a simple minesweeper game for a school project, in which every field is an instance of the Field class which inherits JButton.我目前正在为学校项目构建一个简单的扫雷游戏,其中每个字段都是继承 JButton 的 Field 类的实例。 Here's (most of) the class in its current state:这是(大部分)当前状态的类:

public class Field extends JButton implements MouseListener {

    public Field() {
        super(" ");
        setFocusable(false);
        addMouseListener(this);
        setFont(new Font("sans serif", Font.PLAIN, 20));
    }

    @Override
    public void mouseClicked(MouseEvent me) {
        //...
    }

}

These fields then basically get added to a MineField object, which inherits JPanel.然后,这些字段基本上被添加到继承 JPanel 的 MineField 对象中。 Here's the code for that, too:这也是代码:

class MineField extends JPanel {

    Field[][] fields;

    public MineField(int x, int y, int m) {
        fields = new Field[x][y];

        setLayout(new GridLayout(x, y));
        for (int i = 0; i < x; i++) {
            for(int j = 0; j < y; j++) {
                fields[i][j] = new Field();
                add(fields[i][j]);
            }
        }
        //...
    }

}

The size of the minefields are arbitrary, and are generated according the what difficulty the user chooses from the JMenuBar, with these methods:雷区的大小是任意的,根据用户从 JMenuBar 中选择的难度来生成,使用这些方法:

    private void startBeginner() { startGame(8, 8, 10); }

    private void startIntermediate() { startGame(16, 16, 40); }

    private void startAdvanced() { startGame(16, 30, 99); }

    private void startGame(int x, int y, int m) {
        if(mineField != null) {
            remove(mineField);
        }

        mineField = new MineField(x, y, m);

        add(mineField, BorderLayout.CENTER);

        // ...
    }

Most of what I created for now seems to work, with one exception.我现在创建的大部分内容似乎都有效,只有一个例外。 That being when I want to start a new game of the same difficulty of my current one.那时我想开始一款与当前难度相同的新游戏。 What happens is that all the fields disappear form the window, which has a blank MineField (although I'm not sure, that might not even be there, too).发生的情况是所有字段都从窗口中消失了,该窗口有一个空白的 MineField(虽然我不确定,它甚至可能不存在)。 How could I solve this issue?我怎么能解决这个问题?

This works for me:这对我有用:

When you want to remove the old board JPanel, and create a new one.当你想删除旧板JPanel,并创建一个新的。 First, remote it by calling the container panel (its parent)首先,通过调用容器面板(它的父级)来远程控制它

parent.removeAll()

Now, addyour new board JPanel to parent JPanel like you did:现在,像您一样将您的新板 JPanel 添加到父 JPanel:

parent.add(mineField, BorderLayout.CENTER);

Then, by using the JFrame methods, refresh GUI by 2 methods one by one:然后,通过使用 JFrame方法,通过 2 种方法一一刷新 GUI:

this.revalidate();
this.repaint();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM