我需要以编程方式将UI组件添加到现有的JPanel。我无法使我添加的组件出现。
注意:
主类:
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();
}
}
答案 0 :(得分:3)
您正在使用GroupLayout
jPanel1
(当您使用像NetBean的GUI生成器这样的IDE时)但是您尝试在JLabel
内添加一个组件(addAnotherPanel()
)直接使用jpanel1.add(component)
函数。您不需要将组件直接添加到容器中 - 使用GroupLayout
方法之一时addComponent
隐式地为您完成。
但是,GroupLayout
并非设计为在使用手动编码布局组件时使用。尝试以编程方式学习其他LayoutManager
布局组件。
查看How to Use GroupLayout了解详情。