java 动态按钮,在Java中动态生成按钮

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 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值