我在这里粘贴下面的代码。我对此感到困惑:为什么没有将JButton添加到JPanel中,即使事件被正确地聆听和响应。
感谢您的帮助。
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();
}
}