[英]how to set the height of a dynamically created jpanel?
我无法使用setPreferredSize函数设置动态创建的JPanel大小。 还有其他方法吗?
main_panel.removeAll();
main_panel.revalidate();
main_panel.repaint();
panel = new JPanel[100];
Login.session = Login.sessionfactory.openSession();
Login.session.beginTransaction();
String select_n_p_4 = "select a.triage_id from PC_TRIAGE_MASTER_POJO a";
org.hibernate.Query query1 = Login.session.createQuery(select_n_p_4);
List l3 = query1.list();
Iterator it3 = l3.iterator();
while (it3.hasNext()) {
Object a4 = (Object) it3.next();
int f = (int) a4;
main_panel.setLayout(new GridLayout(0, 1, 1, 10));
panel[ind] = new JPanel();
panel[ind].setPreferredSize(new Dimension(10, 10));
panel[ind].setBorder(triage_boder);
count++;
main_panel.add(panel[ind]);
main_panel.revalidate();
main_panel.repaint();
ind++;
}
您的问题是您使用的布局管理器。 GridLayout基于父组件的大小创建一个统一的网格,并将组件手动适合每个单元格。 您的代码似乎暗示您想为l3中的每个元素创建一个10 x 10的JPanel,每个元素都呈现在另一个元素的上方,并以10像素分隔。 在使用BoxLayout的程序上下文中,这是一种可能的方法,该方法确实使用单个组件的大小:
Dimension dim = new Dimension(10, 10);
main_panel.setLayout(new BoxLayout(main_panel, BoxLayout.PAGE_AXIS));
for (Iterator it3 = l3.iterator; it3.hasNext(); ) {
panel[ind] = new JPanel();
panel[ind].setPreferredSize(dim);
panel[ind].setMaximumSize(dim);
main_panel.add(panel);
main_panel.add(Box.createRigidArea(dim));
count++;
ind++;
}
// you probably don't need this call
main_panel.revalidate();
在大多数情况下,仅应设置一次组件的布局,而不是每次添加组件时都应设置一次。 使用revalidate / repaint,只有在运行时添加/删除组件时 ,才必须调用这些方法。 祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.