JPanel不可见

时间:2013-10-29 03:58:20

标签: java swing jpanel actionlistener menuitem

我正在尝试使用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
    }
});

1 个答案:

答案 0 :(得分:3)

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

@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。

相关问题