2015-12-22 88 views
-3

我想生成多個面板(以標題,說明和詳細按鈕),這是一般結構:動態添加jpanels

enter image description here

但是,當我在for循環把這個代碼,它總是添加最後一個項目。

Panel panel_1 = new Panel(); 
panel_1.setBounds(23, 134, 378, 208); 

JLabel lblNewLabel_2 = new JLabel("desc"); 
lblNewLabel_2.setBounds(0, 69, 189, 69); 

JButton btnNewButton_2 = new JButton("Details"); 
btnNewButton_2.setBounds(104, 139, 189, 69); 
panel_1.setLayout(null); 

JLabel lblPrv = new JLabel("title"); 
lblPrv.setBounds(104, 0, 189, 69); 
panel_1.add(lblPrv); 
panel_1.add(lblNewLabel_2); 

JLabel label_1 = new JLabel(""); 
label_1.setBounds(0, 69, 189, 69); 
panel_1.add(label_1); 

panel_1.add(btnNewButton_2); 

任何建議?

+1

請不要在標題中添加標籤。我爲你刪除了它們。 – Tom

+3

使用佈局管理器的組合,請參閱[佈置容器中的組件](http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html)以獲取更多詳細信息 – MadProgrammer

+2

Java GUI必須處理不同的操作系統',屏幕大小,屏幕分辨率等使用不同的地區不同的PLAF。因此,它們不利於像素的完美佈局。請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[white space]的佈局填充和邊框(http://stackoverflow.com/a/17874718/ 418556)。 –

回答

1

下面是如何將多個面板爲例彼此相鄰:

enter image description here

public class Example extends JFrame { 

    Example() { 

     setLayout(new FlowLayout()); 
     for (int i = 0; i < 4; i++) 
      add(new MyPanel()); 

     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     pack(); 
     setVisible(true); 
    } 

    class MyPanel extends JPanel { 

     MyPanel() { 

      setLayout(new BorderLayout()); 
      add(new JLabel("title", SwingConstants.CENTER), BorderLayout.PAGE_START); 
      add(new JLabel("<html>WWWWWW WWWWWWW<p>WWWWWWWWW<p>RRRRRRR RRRRR RRRRRRR")); 
      add(new JButton("Details"), BorderLayout.PAGE_END); 
     } 
    } 

    public static void main(String[] args) { 

     SwingUtilities.invokeLater(() -> new Example()); 
    } 
} 

你應該選擇的佈局管理器最適合您的情況。

+0

每次如何換行? – Fr4ncx

+0

@ Fr4ncx包裹什麼? – user1803551

+0

每個面板... – Fr4ncx