views:

63

answers:

3

Hi,

I'm fairly new to Java and I've been having some difficulties with Swing. I'm trying to create a very simple GUI program which should be create a set of buttons but my code doesn't work.

Here's my code;

myPanel = new JPanel();

JButton myButton = new JButton("create buttons");
myButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        int val = Integer.parseInt(textfield.getText());
        for(int i = 0; i < val; i++) {
            JButton button = new JButton("");
            button.setText(String.valueOf(i));
            myPanel.add(button);
        }
    }
});

But nothing happens when I click to "create buttons" button. Can anyone tell me what I'm missing?

+2  A: 

You need to refresh panels that are already running with revalidate:

myPanel.revalidate()

Mike42
Not sure, but shouldn't he pack() too ?
Raveline
I suppose he called pack on the JFrame that he's adding the JPanel on.
walters
`pack` should be used to adjust the size of the component. If it is fixed size there is no need to call `pack`.
Carlos Heuberger
A: 

You might have to invoke the validate method on the myPanel to get the contents of the GUI to update, after adding a button on the panel. Also consider the use of IDEs(Netbeans, Eclipse, IntelliJ Idea etc...), that's if it's necessary, for GUI building.

walters
A: 

Have you tried throwing a print statement in there to verify the action listener is actually being activated? Also, don't you have to set the location and size for the buttons to be visible?

Koop