问题描述
我正在尝试动态生成表单.基本上,我想加载要购买的项目列表,并为每个项目生成一个按钮.我可以确认按钮是用调试器生成的,但没有显示.这是在 JPanel
的子类中:
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
是 JButton
的子类.有什么想法吗?
DrinkButton
is a subclass of JButton
. Any ideas?
推荐答案
适用于我的电脑...
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 按钮网格)并确定您的代码有什么问题.
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.
这篇关于Java中按钮的动态生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!