I’m working on a program and I want to create an app in which I can repeat the gui components using the for loop. I’ve done this using card layout and it works fine but when I use container and JPanel without card layout the gui components overlap on the previous components. Please give me a hint or advise where my code is wrong. Thanks for your advise and time in advance.
Here’s the code of my app:
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);
}
}
You have set the layout of the
ccpanel tonull, which is not a good idea. Then, using thesetBounds(x, y, width, height)you set the location and size of the components that you add and they of course overlap.Try to use any layout manager that fits your needs, but don’t set it to null unless you really have a very strong reason to do that.