无法动态添加JPanel到JFrame

时间:2011-12-24 07:20:30

标签: java model-view-controller swing miglayout

我要观点:

  1. MainWindowView(扩展JFrame)
  2. ScanOptimisationView(扩展JPanel)
  3. 所以,我在MainWindowView类中有组合框。然后我创建ActionListener并将其绑定到这个组合框。此ActionListener的actionPerfomed()方法尝试将ScanOptimisationView面板添加到主窗口框架。这是代码:

    package ru.belaventcev.view;
    
    import java.awt.Container;
    
    public class MainWindowView extends JFrame{
        private int frmHeight = 525;
        private int frmWidth  = 650;
    
        public Container frmContainer;
    
        public static JButton btnCalc;
    
        public static JComboBox cbMethods;
    
        public MainWindowView(){
            setPreferredSize(new Dimension(frmWidth, frmHeight));
            setSize(frmWidth, frmHeight);
            setLocationRelativeTo(null);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setResizable(false);
            frmContainer = getContentPane();
            frmContainer.setLayout(new MigLayout("", "[grow,center]", "[::30px,grow,center][grow,center][::500px,grow,center][::25px,grow,center]"));
            cbMethods = new JComboBox();
            cbMethods.setModel(new DefaultComboBoxModel(new JPanel[] {new ScanOptimisationView()}));
            cbMethods.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    JPanel temp = (JPanel) cbMethods.getSelectedItem();
                    frmContainer.add(temp, "cell 0 1,span");
                }
            });
    
            /*
             * If I uncomment this, panel is shown!
            JPanel temp = (JPanel) cbMethods.getSelectedItem();
            frmContainer.add(temp, "cell 0 1");
            */
    
            frmContainer.add(cbMethods, "cell 0 0,growx");
    
    
    
            btnCalc = new JButton("Расчитать");
            frmContainer.add(btnCalc, "cell 0 3,alignx right");
    
        }
    }
    

    你能帮助我理解 - 为什么面板没有在actionPerformed()中显示代码,但是当我使用下面的代码时会显示它?

1 个答案:

答案 0 :(得分:5)

在非工作案例中,在actionListener调用frmContainer.add()后,您需要调用frmContainer.validate()。来自Container.add()的Javadocs:

“如果已将组件添加到已显示的容器 ,则必须在该容器上调用validate以显示新组件。”

当你回复点击时,显然已经显示了你的容器。当您在构造函数中添加JPanel时,您的JFrame尚未显示。