2012-10-02 97 views
2

我正在开发一个程序,我想创建一个应用程序,在该应用程序中我可以使用for循环重复使用gui组件。我已经完成了这个使用卡布局,它工作正常,但是当我使用容器和JPanel没有卡布局gui组件重叠在以前的组件。请给我一个提示或建议我的代码错误的地方。感谢您的建议和时间提前。动态添加gui组件?

这里是我的应用程序的代码:

class form extends JFrame implements ActionListener { 

    JTextArea text; 
    static int openFrameCount = 0; 
    public form(){ 
      super("Insert Form"); 
     Container panel=getContentPane(); 
     JPanel cc = new JPanel(); 
     cc.setLayout(null); 
     for(int i=1;i<=2;i++){ 
     JLabel label1=new JLabel(" Question"+(++openFrameCount)); 

     label1.setBounds(15, 40, 185, 50); 
     cc.add(label1); 
     text=new JTextArea(); 
       text.setLineWrap(true); 
     text.setWrapStyleWord(true); 
     text.setPreferredSize(new Dimension(750,50)); 
     text.setBounds(80, 60,750,50); 
     cc.add(text); 
     JLabel symbol=new JLabel("Selection for Option?"); 
     symbol.setBounds(100, 120,850,60); 
cc.add(symbol); 
    ButtonGroup group = new ButtonGroup(); 
    JRadioButton rbut=new JRadioButton("Radio Button for option"); 

     rbut.setBounds(300, 120,300,60); 
     JCheckBox cbox=new JCheckBox("Check Box for option"); 
     cc.add(rbut); 
     cbox.setBounds(650, 120,350,60); 
     cc.add(cbox); 
     group.add(rbut); 
     group.add(cbox); 

      cc.revalidate(); 
validate(); 


     panel.add(cc); 
     } 
    } 

回答

2

你有cc面板的布局设置为null,这是不是一个好主意。然后,使用setBounds(x, y, width, height)设置您添加的组件的位置和大小,它们当然会重叠。

尝试使用适合您需求的布局管理器,但不要将其设置为null,除非您确实有非常强的理由这样做。

+0

感谢您的建议是它的工作,通过设置布局流布局以及卡布局 – janat