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.