【问题标题】:Can't add JPanel to JFrame on the fly无法即时将 JPanel 添加到 JFrame
【发布时间】:2012-01-27 05:47:08
【问题描述】:

我要观点:

  1. MainWindowView(扩展 JFrame)
  2. ScanOptimisationView(扩展 JPanel)

所以,我在 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() 中面板没有显示代码,但是当我使用下面的代码时它会显示?

【问题讨论】:

    标签: java model-view-controller swing miglayout


    【解决方案1】:

    在不工作的情况下,你的actionListener调用frmContainer.add()后,你需要调用frmContainer.validate()。来自 Container.add() 的 Javadocs:

    “如果一个组件被添加到一个容器中已经显示,必须在那个容器上调用 validate 来显示新的组件。”

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

    【讨论】:

    • 效果很好!谢谢!我需要更加关注文档:)
    猜你喜欢
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多