Swing:动态显示面板

Don*_*Don 2 java swing netbeans interface-builder

我目前正在使用Netbeans GUI构建器创建一个java swing GUI.我有一堆面板正在我的主JFrame上被替换,因为用户导航GUI并且控制器类正在处理这个问题.但是,有一个步骤(FilterDefinitionPanel)包含一个组合框以及一个空白内部面板(QueryHelperPanel).

我想要做的是根据用户在组合框中选择的内容将这个内部面板替换为我创建的另一个内部面板(StringQueryDefinitionPanel).现在,在我的组合框的ComboBoxItemStateChanged事件处理程序下,我的控制器类运行此方法:

 public void selectFilterAttribute(Object item) {
    /**
     * Determine panel to create based on item selection. Currently always returns the same
     * StringQueryDefinitionPanel.
     */
    JPanel panel = this.getRequiredQueryHelperPanel(item);
    /**
     * Swap the placeholder QueryHelperPanel with the required one.
     */
    ((FilterDefinitionPanel) this.mainFrame.getMainPanel()).setQueryHelperPanel(panel);
    /**
     * Not sure if all of these are needed :\
     */
    mainFrame.validate();
    mainFrame.repaint();
    mainFrame.pack();
}
Run Code Online (Sandbox Code Playgroud)

这就是FilterDefinitionPanel的setQueryHelper方法中发生的事情:

public void setQueryHelperPanel(JPanel panel){
    this.remove(queryHelperPanel);
    this.queryHelperPanel=panel;
    this.queryHelperPanel.repaint();
    /**
    * Again, not sure which refresh methods are needed...
    */
    this.validate();
    this.repaint(); 
}
Run Code Online (Sandbox Code Playgroud)

目前我认为这是用...替换我的内部占位符面板......但是替换似乎什么都没有.我不知道它是否重要但占位符和替换面板的大小相同.我是一个摇摆小块,所以任何提示都会非常感激.

Mic*_*rdt 7

setQueryHelperPanel()方法不起作用,因为它this通过remove()方法从子集合中删除现有面板,但不add()用于添加新面板 - 将其分配给实例变量不会导致它成为子节点.

但是,对您的问题更清晰的解决方案是使用CardLayout.