我需要以编程方式将 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();
}
}
最佳答案
您正在使用 GroupLayout
和 jPanel1
(当您使用像 NetBean 的 GUI 生成器这样的 IDE 时),但您正在尝试添加一个组件(JLabel
) >) 在 addAnotherPanel()
函数中直接使用 jpanel1.add(component)
函数。您不需要将组件直接添加到容器中,这是在使用 addComponent
方法之一时由 GroupLayout
隐式为您完成的。
但是,GroupLayout
并非设计用于使用手动编码布局组件。尝试学习其他 LayoutManager
以编程方式布局组件。
检查How to Use GroupLayout了解详情。
关于java - 无法以编程方式添加到 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20334554/