且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java中动态生成按钮

更新时间:2022-10-14 23:30:35

在我的电脑上工作...

  public class Panel扩展JPanel {

public Panel(){
setLayout(new java.awt.GridLayout(4,4)); (int i = 0; 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网格的按钮),并确定你的代码有什么问题。


I am trying to dynamically generate a form. Basically, I want to load a list of items for purchase, and generate a button for each. I can confirm that the buttons are being generated with the debugger, but they aren't being displayed. This is inside a subclass of 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();
}

DrinkButton is a subclass of JButton. Any ideas?

Works on my computer...

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

As far as I remember your version was working as well, although I had to remove your "drinking" code. Start from this example (it shows nice 4x4 grid of buttons) and determine what is wrong with your code.