2015-03-25 26 views
0

我无法使用setPreferredSize函数设置动态创建的JPanel大小。还有其他方法吗?如何设置动态创建的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++; 
     } 
+0

让我们从'[应该避免使用Java Swing中的set(Preferred | Maximum | Minimum)尺寸方法?](http://stackoverflow.com/questions/7229226/should-i-avoid-the- use-of-setpreferredmaximumminimumsize-methods-in-java-swi)'然后问什么'main_panel'用于布局管理器 – MadProgrammer 2015-03-25 04:05:16

+0

为什么你不能? – Mordechai 2015-03-25 04:05:58

回答

0

你的问题是你使用的布局管理器。 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(); 

在大多数情况下,你应该只设置一个组件的布局一次,而不是每次添加一个零件。通过重新验证/重新绘制,您只需要调用这些方法if you add/remove components at runtime。祝你好运!