每次调用actionPerformed时添加组件

时间:2018-07-16 15:22:18

标签: java swing

大家好,我一直在尝试做一个小程序,它只是一个带有JButton的窗口,该窗口在点击时打开JOptionPane,让我输入休假列表的条目。我想在每次执行JCheckBox的操作时,将该条目作为JLabel添加到JButton中。我目前的问题是,即使我的代码看起来工作正常,在将字符串输入到JCheckBox之后,JOptionPane也不会显示。它可能与actionPerformed是无效方法有关吗?我很乐意提供帮助,如果这个问题已经发生,但我在任何地方都找不到,很抱歉。

提前谢谢!

我的代码:

public class Urlaub extends JFrame {

    public Urlaub() {
        super("Urlaub");
        JFrame window = this;
        window.setSize(800, 600);
        window.setLocationRelativeTo(null);
        window.setVisible(true);

        JLabel grouped = new JLabel();
        window.add(grouped);

        grouped.setLayout(new FlowLayout());

        JButton addThing = new JButton("Add things");
        addThing.setVisible(true);
        grouped.add(addThing);
        addThing.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                String entry = JOptionPane.showInputDialog(this, "Enter item");
                JCheckBox checkItem = new JCheckBox(entry);
                grouped.add(checkItem); // this is the line which should add the JCheckBox to the JLabel/Window 
            }
        });
    }
}

1 个答案:

答案 0 :(得分:2)

更改容器的子级后,您需要revalidate。这将强制重新粉刷。

您还将元素添加到JLabel中,这很不常见。最好使用JPanel

        super("Urlaub");
        JFrame window = this;
        window.setSize(800, 600);
        window.setLocationRelativeTo(null);
        window.setVisible(true);

        JPanel grouped = new JPanel();
        window.getContentPane().add(grouped);
        grouped.setLayout(new FlowLayout());

        JButton addThing = new JButton("Add things");
        grouped.add(addThing);
        grouped.add(new JCheckBox("je"));
        addThing.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                String entry = JOptionPane.showInputDialog(this, "Enter item");
                JCheckBox checkItem = new JCheckBox(entry);
                grouped.add(checkItem); // this is the line which should add the JCheckBox to the JLabel/Window#
                window.getContentPane().revalidate();
            }
        });