将新组件添加到另一个 class 中创建的 JPanel

Add a new component to a JPanel created in another class

我有一个 JFrame,网格为 JPanels(使用 Borderlayout)。每个 JPanel 包含一个 JButton(扩展到全尺寸,因为在 Borderlayout 内)。所以我有扫雷之类的东西。

这些按钮有一个侦听器,带有构造函数 Listener(panel),因此我可以使用侦听器中的面板。

如果我在侦听器中执行 panel.removeAll(); 然后按钮消失,但 JPanel 仍然存在,所以我得到一个免费的 space.

我做了 panel.setBackground(Color.pink); 并且它有效,但是如果我想添加一个组件,例如另一个按钮或 JLabel,它不起作用。它在相同的 class 中工作但不分开,或者在 class.

的方法中工作

谢谢。希望您能理解!

这是我的听众class:

public class ListenerCasillas implements ActionListener {

    JPanel panel;

    ListenerCasillas(JPanel panel){

    this.panel = panel;

    }

    @Override
    public void actionPerformed(ActionEvent e) {

        panel.removeAll();//works
        panel.setBackground(Color.green);//works
        panel.add(new JLabel("1"));//doesn't work
        panel.repaint();//works

    }

}

这里是创建网格的 class:

public class Game extends JFrame {
    Game(){
        super("MineSweeper 0.0");
        setLocation(300, 300);
        setResizable(false);

        setLayout(new GridLayout(mainclass.rows, mainclass.cols));

        Dimension d = new Dimension(30, 30);

        for(int i = 0; i < mainclass.rows; i++){
            for(int j = 0; j < mainclass.cols; j++){
                JPanel panel = new JPanel();
                panel.setLayout(new BorderLayout());
                panel.setPreferredSize(d);

                add(panel);

                JButton boton = new JButton();

                boton.addActionListener(new ListenerCasillas(panel));
                panel.add(boton);
            }
        }

        setVisible(true);
        pack();
    }
}

完整java项目(如果你想测试): https://drive.google.com/file/d/0B0WNwgY4eOjvNmNHM0E5U0FxVGc/view?usp=sharing

解决方案是在您的 ListenerCasillasactionPerformed() 方法中调用 revalidate()

public class ListenerCasillas implements ActionListener {
    JPanel panel;

    ListenerCasillas(JPanel panel){
        this.panel = panel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        panel.removeAll();
        panel.setBackground(Color.green);
        panel.add(new JLabel("1"));
        panel.revalidate();
        panel.repaint();
    }
}

有关 repaint()revalidate() 的更多信息,请查看 SO 上的 this brilliant answer