无法以编程方式添加到JPanel

时间:2013-12-02 17:45:56

标签: java swing user-interface jpanel

我需要以编程方式将UI组件添加到现有的JPanel。我无法使我添加的组件出现。

注意:

  • 几乎所有的TestUI代码都是由NetBeans生成的(我的方法在底部)
  • 我试图根据我遇到的其他答案设置jPanel1.validate(),jPanel1prevalidate()和pack()

主类:

public class Test {

    public static void main(String[] args) {
        TestUI testUI = new TestUI();
        testUI.setVisible(true);
        testUI.addAnotherPanel();
    }    
}

UI类:

import javax.swing.JLabel;

public class TestUI extends javax.swing.JFrame {

    /**
     * Creates new form TestUI
     */
    public TestUI() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    // Variables declaration - do not modify                     
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   

    void addAnotherPanel() {
        jPanel1.add(new JLabel("Hello World."));
        jPanel1.revalidate();
    }
}

1 个答案:

答案 0 :(得分:3)

您正在使用GroupLayout jPanel1(当您使用像NetBean的GUI生成器这样的IDE时)但是您尝试在JLabel内添加一个组件(addAnotherPanel())直接使用jpanel1.add(component)函数。您不需要将组件直接添加到容器中 - 使用GroupLayout方法之一时addComponent隐式地为您完成。

但是,GroupLayout并非设计为在使用手动编码布局组件时使用。尝试以编程方式学习其他LayoutManager布局组件。 查看How to Use GroupLayout了解详情。