2015-12-22 90 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