java swing重绘按钮

时间:2011-07-22 01:00:24

标签: java swing

我在这里粘贴以下代码。我很困惑:为什么JPanel中没有添加JButton,即使事件被正确地监听和响应。

感谢您的帮助。

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();
    }
}

2 个答案:

答案 0 :(得分:5)

无论何时在Container上添加新组件,都应该调用revalidate并重新绘制:

           for (int i = 0; i < n; i++) {
              jPanel2.add(new JButton(Integer.toString(i)));
           }
           jPanel2.revalidate();
           jPanel2.repaint();

第一个告诉布局管理器做他们的事情,第二个让java paint manager重新绘制容器以重绘脏位。

修改
根据mKorbel的出色建议,revalidate和repaint方法移出循环。

答案 1 :(得分:2)

按下该键后,您需要在JPanel上致电repaint / validate