[英]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.