Reputation: 39
i want to add 10 jlabel and 10 jbutton unto each jpanel. Now there are 10 jpanels which i want to add to a frame, so the jframe should show 100 jlabel, 100 jbutton with 10 jpanels. My problem is that the frame only shows 10 jlabel and 10 jbutton. i dunno where am wrong. here is my code
public class MultiPanel extends JFrame {
private JPanel[] panel;
private JLabel[] label;
private JButton[] button;
public MultiPanel() {
panel = new JPanel[10];
label = new JLabel[10];
button = new JButton[10];
for (int i = 0; i < label.length; i++) {
label[i] = new JLabel(String.valueOf(i + 1));
button[i] = new JButton("B");
label[i].setSize(50, 50);
panel[i] = new JPanel();
panel[i].setLayout(new FlowLayout(FlowLayout.CENTER));
panel[i].add(label[i]);
panel[i].add(button[i]);
add(panel[i]);
}
setLayout(new GridLayout(1, 10));
setSize(720, 560);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MultiPanel m_pnl = new MultiPanel();
}
}
Upvotes: 0
Views: 678
Reputation: 2646
public class MultiPanel extends JFrame {
public MultiPanel() {
int increment = 0;
while(increment < 10){
JPanel toAdd = new JPanel();
for (int i = 0; i < 10; i++) {
JLabel l = new JLabel(String.valueOf(i + 1));
JButton b = new JButton("B");
l.setSize(50, 50);
toAdd.setLayout(new FlowLayout(FlowLayout.CENTER));
toAdd.add(l);
toAdd.add(b);
}
add(toAdd);
increment++;
}
setLayout(new GridLayout(1, 10));
setSize(720, 560);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MultiPanel m_pnl = new MultiPanel();
}
}
Your logic was faulty... Try this. You have an outer while
loop that will create 10 JPanels
like you want. The inner for
loop adds 10 JLabels
and JButtons
to each JPanel
like you want. Then you just add all ten JPanels
to the main JPanel
which is slapped on the JFrame
. I have compiled and run this and it works
Before you were only adding one label and button to each panel. You had 10 panels each with 1 button and one label
Upvotes: 1