Possible Duplicate:
java - How would I dynamically add swing component to gui on click?
I want to add array of buttons dynamically. I tried like this:
this.pack();
Panel panel = new Panel();
panel.setLayout(new FlowLayout());
this.add(panel);
panel.setVisible(true);
for (int i = 0; i < Setting.length; i++) {
for (int j = 0; j < Setting.width; j++) {
JButton b = new JButton(i+"");
b.setSize(30, 30);
b.setLocation(i * 30, j * 30);
panel.add(b);
b.setVisible(true);
}
}
but didn't get anything , what mistake did I make?
Edit
I have jFrame class "choices" on it i have a button , when I press the button, this is supposed to happen:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
structure.Setting s = new Setting(8, 8, 3, 1, 1);
Game g = new Game();
g.setSetting(s);
this.dispose();
g.show();
}
then i go to the Game class (also jFrame class) to the function setSetting and it is like this:
void setSetting(Setting s) {
this.setting = s;
structure.Game game = new structure.Game(setting);
JPanel panel = new JPanel(new GridLayout(5, 5, 4, 4));
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
JButton b = new JButton(String.valueOf(i));
panel.add(b);
}
}
add(panel);
pack();
setVisible(true);
}
structure.Setting setting;
}
The
JPanel
is already under the control of a layout manager, setting the size and position of the buttons is irrelevant, as they will changed once the panel is validated.Try, instead, adding the panel AFTER you've populated it with buttons..
UPDATED with Example
Without further evidence, we are only guessing...You now have two people who have no issues.
setBound method
You may use GridLayout to add equal height/width buttons:
and code in button's handler should be:
Note that you can also pass
Setting
object reference viaGame
constructor (when you may add widgets dynamically) instead of callingsetSetting
method.I am guessing that
this
extens or is some kind of frame?First step is to pack the frame by doing
this.pack();
sets the frame size ti just fit all objects.I assume you have set it to visible?
Now you should be able to see the buttons. If you want a different layout use
panel.setLayout(new SomeLayout);