0

我正在尝试使用 JMenuItem 删除和添加我需要的面板。然而,当我使用动作监听器并告诉它添加一个面板时,什么都没有发生。

PanelMaker newPanel = new Panel(); //I have my panel in another class and I use this to call it
item.addActionListener(new ActionListener() {   
    @Override
    public void actionPerformed(ActionEvent e) {
       add(newPanel.pane());//I try to add the panel here, but nothing occurs
    }
});
4

1 回答 1

3

您需要重新验证并重新绘制添加或删除组件的容器。IE,

@Override
public void actionPerformed(ActionEvent e) {
    add(newPanel.pane());//I try to add the panel here, but nothing occurs
    revalidate(); // tells the layout managers to re-layout components
    repaint();  // requests that the repaint manager repaint the container
}

调用revalidate()告诉容器的布局管理器重新布局它持有的所有组件,同样可能导致所有包含的容器的级联重新布局。

再次调用向repaint()重绘管理器建议重绘容器及其所有子容器。这很重要,特别是如果组件被移除或组件移动到之前看到另一个组件的位置的顶部,以便清理旧的渲染。

同样非常重要的是容器使用的布局管理器。有些人不容易接受新组件——在这方面,GroupLayout 立即浮现在脑海。

于 2013-10-29T03:59:31.013 回答