Reputation: 10855
I am pasting the following code here. I am puzzled at: why there are no JButtons added into the JPanel, even though the event was correctly listened and responded.
Thank you for your help.
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class PanelControlButtons extends JFrame {
private JPanel jPanel1 = new JPanel();
private JPanel jPanel2 = new JPanel();
private JPanel jPanel = new JPanel();
private JTextField jtf = new JTextField(20);
public PanelControlButtons() {
setSize(400, 300);
getContentPane().add(jPanel);
jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.X_AXIS));
jPanel2.setLayout(new BoxLayout(jPanel2, BoxLayout.X_AXIS));
jPanel.add(jPanel1);
jPanel.add(jPanel2);
jPanel2.add(new JButton("abc"));
for (int i = 0; i < 3; i++) {
jPanel2.add(new JButton(Integer.toString(i)));
}
jPanel1.add(jtf);
jPanel2.setLayout(new BoxLayout(jPanel2, BoxLayout.X_AXIS));
jtf.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
System.out.println("ENTER pressed");
int n = Integer.parseInt(jtf.getText());
System.out.println(n);
for (int i = 0; i < n; i++) {
jPanel2.add(new JButton(Integer.toString(i)));
}
}
}
});
setVisible(true);
}
public static void main(String[] args) {
PanelControlButtons panelControlButtons = new PanelControlButtons();
}
}
Upvotes: 2
Views: 2972
Reputation: 285405
Anytime you add a new component on a Container, you should call revalidate and repaint:
for (int i = 0; i < n; i++) {
jPanel2.add(new JButton(Integer.toString(i)));
}
jPanel2.revalidate();
jPanel2.repaint();
The first to tell the layout managers to do their thing, the second to have the java paint manager repaint the container to redraw the dirty bits.
Edit
The revalidate and repaint methods moved out of loop as per mKorbel's excellent recommendation.
Upvotes: 5
Reputation: 930
you need to call repaint/validate on your JPanel
after the key is pressed
Upvotes: 2