Kiril
Kiril

Reputation: 272

not displaying all the buttons

I have an array with buttons:

JButton[] commandButtons = {
    new JButton("Add Chair"),
    new JButton("Add Table"),
    new JButton("Add Desk"),
    new JButton("Clear All"),
    new JButton("Total Price"),
    new JButton("Save"),
    new JButton("Load"),
    new JButton("Summary")
        };

I want to put them all in the panel, but it is displaying only the last button. so if anyone know how to fix it or have an advice it would be great.

Also I am not sure how to do the for loop as a for each.

for(int i=0; i<commandButtons.length; i++)      
    {
    westPanel.add(commandButtons[i]);
        commandButtons[i].addActionListener(this);
    }

Upvotes: 0

Views: 39

Answers (3)

Perry Monschau
Perry Monschau

Reputation: 901

Yeah it depends on the layout manager. If you want no layout manager you have to set the location and size yourself, otherwise they'll all be 0,0.

setLayout(null); //gives no layout manager

Always try to use a layout manager though.

Upvotes: 1

AlexR
AlexR

Reputation: 115328

I believe that you have not set layout, so the default one is BorderLayout. When you are adding elements to this layout without telling the parameter (where to put the element) it is added by default to the center. But there can be only one element in the center, so you see only the last button.

The fast fix is define flow layout:

pannel.setLayout(new FlowLayout());

Do it before adding the buttons. Now you will see all buttons. If you do not see enlarge the window.

Now, if the layout is not what you really want, read about layouts and decide which one (or combination of them) do you need.

Upvotes: 1

Java42
Java42

Reputation: 7706

Set a FlowLayout manager on the westPanel JPanel and they will all show up.

Upvotes: 1

Related Questions