【问题标题】:Add a new component to a JPanel created in another class将新组件添加到在另一个类中创建的 JPanel
【发布时间】:2026-02-10 14:40:01
【问题描述】:

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

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

如果我在侦听器中执行panel.removeAll();,那么按钮就会消失,但JPanel 仍然存在,所以我得到了一个空闲空间。

我做了panel.setBackground(Color.pink);,它可以工作,但如果我想添加一个组件,比如另一个按钮或JLabel,它就不起作用。它在同一个类中工作,但不能分开,或者在类的方法中。

谢谢。希望你能理解!

这是我的监听类:

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

    }

}

这里是创建网格的类:

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

【问题讨论】:

  • 如果将panel.repaint(); 移动到actionPerformed 的末尾会发生什么?在修改它的过程中告诉它重新绘制似乎很奇怪
  • @phflack 只是为了移除按钮,我改变了它但它是一样的。
  • 有道理,因为添加组件应该强制重绘。如果您将Dimension d = new Dimension(30, 30); 更改为更大的值会怎样? 300x300 应该有足够的空间来呈现标签(用于测试)
  • @phflack 没什么,非常大的绿色方块。

标签: java swing jpanel awt jlabel


【解决方案1】:

解决方案是在您的ListenerCasillass actionPerformed() 方法中调用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

【讨论】:

    最近更新 更多