Java中动态生成按钮

3

我正在尝试动态生成一个表单。基本上,我想加载一个可购买物品的列表,并为每个物品生成一个按钮。我可以通过调试器确认按钮已经被生成,但它们并没有显示出来。这是在JPanel的子类中进行的:

private void generate() {
    JButton b = new JButton("height test");
    int btnHeight = b.getPreferredSize().height;
    int pnlHeight = this.getPreferredSize().height;
    int numButtons = pnlHeight / btnHeight;

    setLayout(new GridLayout(numButtons, 1));

    Iterator<Drink> it = DrinkMenu.iterator();

    for (int i = 0; i <= numButtons; ++i) {
        if (!it.hasNext()) {
            break;
        }
        final Drink dr = it.next();
        b = new DrinkButton(dr);
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                order.addDrink(dr);
        }});
        add(b);
    }
    revalidate();
}

DrinkButtonJButton 的子类。有什么想法吗?


为什么您先将b设置为JButton,然后在稍后又将其设置为DrinkButton? - RMT
1
请确保这些修改是在事件分派线程中进行的。 - mre
1
基本代码看起来不错。您正在使用关键的revalidate()方法。但我们不知道这段代码的上下文是什么。我们不知道这个面板是否实际上已经添加到框架中。请发布一个SSCCE(http://sscce.org),以演示问题。 - camickr
3个回答

4

关于validate()、revalidate()和repaint()的示例,看起来对于正确输出到GUI是必需的,由一些LayoutManagers进行布局。

编辑:正如trashgod所注意到的那样,我添加了为EDT安排作业。

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class ValidateRevalidateRepaint {

        private JPanel panel;
        private GridBagConstraints gbc;
        private boolean validate, revalidate, repaint;

        public ValidateRevalidateRepaint() {
            validate = revalidate = repaint = false;
            panel = new JPanel(new GridBagLayout());
            gbc = new GridBagConstraints();
            gbc.insets = new Insets(0, 20, 0, 20);
            panel.add(getFiller(), gbc);
            JFrame f = new JFrame();
            f.setJMenuBar(getMenuBar());
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(panel);
            f.getContentPane().add(getRadioPanel(), "East");
            f.getContentPane().add(getCheckBoxPanel(), "South");
            f.setSize(400, 200);
            f.setLocation(200, 200);
            f.setVisible(true);
        }

        private JMenuBar getMenuBar() {
            JMenu menu = new JMenu("change");
            ActionListener l = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    JMenuItem item = (JMenuItem) e.getSource();
                    int n = Integer.parseInt(item.getActionCommand());
                    makeChange(n);
                }
            };
            for (int j = 1; j < 5; j++) {
                String s = String.valueOf(j) + " component";
                if (j > 1) {
                    s += "s";
                }
                JMenuItem item = new JMenuItem(s);
                item.setActionCommand(String.valueOf(j));
                item.addActionListener(l);
                menu.add(item);
            }
            JMenuBar menuBar = new JMenuBar();
            menuBar.add(menu);
            return menuBar;
        }

        private JPanel getRadioPanel() {
            JPanel panel1 = new JPanel(new GridBagLayout());
            GridBagConstraints gbc1 = new GridBagConstraints();
            gbc1.insets = new Insets(2, 2, 2, 2);
            gbc1.weighty = 1.0;
            gbc1.gridwidth = GridBagConstraints.REMAINDER;
            ButtonGroup group = new ButtonGroup();
            ActionListener l = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    JRadioButton radio = (JRadioButton) e.getSource();
                    int n = Integer.parseInt(radio.getActionCommand());
                    makeChange(n);
                }
            };
            for (int j = 0; j < 4; j++) {
                String s = String.valueOf(j + 1);
                JRadioButton radio = new JRadioButton(s);
                radio.setActionCommand(s);
                radio.addActionListener(l);
                group.add(radio);
                panel1.add(radio, gbc1);
            }
            return panel1;
        }

        private JPanel getCheckBoxPanel() {
            final String[] operations = {"validate", "revalidate", "repaint"};
            ActionListener l = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    JCheckBox checkBox = (JCheckBox) e.getSource();
                    String ac = checkBox.getActionCommand();
                    boolean state = checkBox.isSelected();
                    if (ac.equals("validate")) {
                        validate = state;
                    }
                    if (ac.equals("revalidate")) {
                        revalidate = state;
                    }
                    if (ac.equals("repaint")) {
                        repaint = state;
                    }
                }
            };
            JPanel panel2 = new JPanel();
            for (int j = 0; j < operations.length; j++) {
                JCheckBox check = new JCheckBox(operations[j]);
                check.setActionCommand(operations[j]);
                check.addActionListener(l);
                panel2.add(check);
            }
            return panel2;
        }

        private void makeChange(int number) {
            panel.removeAll();
            for (int j = 0; j < number; j++) {
                panel.add(getFiller(), gbc);
            }
            if (validate) {
                panel.validate();
            }
            if (revalidate) {
                panel.revalidate();
            }
            if (repaint) {
                panel.repaint();
            }
        }

        private JPanel getFiller() {
            JPanel panel3 = new JPanel();
            panel3.setBackground(Color.red);
            panel3.setPreferredSize(new Dimension(40, 40));
            return panel3;
        }

        public static void main(String[] args) {//added Schedule a job for the EDT
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ValidateRevalidateRepaint rVR = new ValidateRevalidateRepaint();
            }
        });
    }
}

1
非常有趣,但不要忽略事件分派线程。 :-) - trashgod
@trashgod :-) 因为我仍然确信,Action是来自Listeners中的ThreadSafe之一 :-) - mKorbel
遗憾的是,线程安全的 API 承诺正在减少,例如 append()append() - trashgod
@trashgod,对于Java7的Swing,他们计划删除EDT的单线程规则,这乍一看似乎是个好主意,但考虑到当前的Java所有者...... - mKorbel

3

在我的电脑上可以正常工作...

public class Panel extends JPanel {

    public Panel() {
        setLayout(new java.awt.GridLayout(4, 4));
        for (int i = 0; i < 16; ++i) {
            JButton b = new JButton(String.valueOf(i));
            b.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    //...
                }
            });
            add(b);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(new Dimension(300, 300));
                frame.add(new Panel());
                frame.setVisible(true);
            }
        });
    }
}

据我所记,你的版本也能正常工作,尽管我不得不删除你的“喝酒”代码。从这个示例开始(它显示了漂亮的4x4按钮网格),确定你的代码有什么问题。

4
你应该在EDT中创建JFrame等对象,以确保程序的正确性和稳定性。 - mre
1
@mre:我不知道那个,我只是选择了我找到的第一个Swing教程来运行代码,这个框架我已经很久没用过了。感谢您的编辑,谢谢! - Tomasz Nurkiewicz
好的例子,但它并没有真正解决动态需求的问题。 - trashgod
事实证明,我的问题出在线程上 - 我没有使用 invokeLater() - Kevin Lacquement

3
您可以使用revalidate(),就像这个示例中展示的那样。
附加说明:这是我对@mKorbel有趣的答案的变化版本,它显示了GridLayout的类似结果。看起来需要在revalidate()之后进行repaint()
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/** @see https://stackoverflow.com/questions/6395105 */
public class ValidateRevalidateRepaint {

    private JPanel center;
    private boolean validate = false;
    private boolean revalidate = true;
    private boolean repaint = true;

    public ValidateRevalidateRepaint() {
        center = new JPanel(new GridLayout(1, 0, 10, 10));
        JFrame f = new JFrame();
        f.setTitle("VRR");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(center, BorderLayout.CENTER);
        f.add(getRadioPanel(), BorderLayout.EAST);
        f.add(getCheckBoxPanel(), BorderLayout.SOUTH);
        makeChange(4);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private JPanel getRadioPanel() {
        JPanel panel = new JPanel(new GridLayout(0, 1));
        ButtonGroup group = new ButtonGroup();
        ActionListener l = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JRadioButton radio = (JRadioButton) e.getSource();
                int n = Integer.parseInt(radio.getActionCommand());
                makeChange(n);
            }
        };
        for (int j = 0; j < 4; j++) {
            String s = String.valueOf(j + 1);
            JRadioButton radio = new JRadioButton(s);
            radio.setActionCommand(s);
            radio.addActionListener(l);
            group.add(radio);
            panel.add(radio);
            if (j == 3) {
                group.setSelected(radio.getModel(), true);
            }
        }
        return panel;
    }

    private JPanel getCheckBoxPanel() {
        final String[] operations = {"validate", "revalidate", "repaint"};
        ActionListener l = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JCheckBox checkBox = (JCheckBox) e.getSource();
                String ac = checkBox.getActionCommand();
                boolean state = checkBox.isSelected();
                if (ac.equals("validate")) {
                    validate = state;
                }
                if (ac.equals("revalidate")) {
                    revalidate = state;
                }
                if (ac.equals("repaint")) {
                    repaint = state;
                }
            }
        };
        JPanel panel = new JPanel();
        for (int j = 0; j < operations.length; j++) {
            JCheckBox check = new JCheckBox(operations[j]);
            if (j == 0) {
                check.setSelected(false);
            } else {
                check.setSelected(true);
            }
            check.setActionCommand(operations[j]);
            check.addActionListener(l);
            panel.add(check);
        }
        return panel;
    }

    private void makeChange(int number) {
        center.removeAll();
        for (int j = 0; j < number; j++) {
            center.add(getFiller());
        }
        if (validate) {
            center.validate();
        }
        if (revalidate) {
            center.revalidate();
        }
        if (repaint) {
            center.repaint();
        }
    }

    private JPanel getFiller() {
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createLineBorder(Color.blue, 5));
        panel.setBackground(Color.red);
        panel.setPreferredSize(new Dimension(50, 50));
        return panel;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ValidateRevalidateRepaint();
            }
        });
    }
}

我忍不住... :-) 我看到你好几次都很讨厌repaint(),是吧 :-),你的例子是OP正确的基础/方法,+1 - mKorbel
@mKorbel:我很重视你的观察,如果你看到repaint()更好的地方,请告诉我。 - trashgod
@trashgod,那是因为我的手速太快了,我犯了一个错误。如果我再读一遍(我写的大傻瓜),那么我要向你道歉,正确的意思是“revalidate()”+“repaint()”,我将其放在所有复合/组合JComponents中,例如JComboBox(通常让我非常生气)。回到我的问题,为什么不使用repaint();? - mKorbel
1
@mKorbel:啊,如果我理解正确,revalidate()并不总是需要一个后续的 repaint();例如:(https://dev59.com/JUnSa4cB1Zd3GeqPNmZP#1439356)。 - trashgod
@trashgod 是的,有时候刷新GUI是自己承担的风险,因为我们错过了API中关于何时/如何/为什么(重新)验证必须重绘的清晰描述。 - mKorbel
@ trashgod 我插队了这个帖子 :-),看起来并不是所有情况都不正确,看看我的帖子。 - mKorbel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接