user3650137
user3650137

Reputation: 41

Buttons not displaying on JPanel

I have the following portion of code:

    buttonPanel = new JPanel();
    back = new JButton("Back");
    close = new JButton("Close");
    addCruise = new JButton("Add new Cruise");
    removeCruise = new JButton("Remove Cruise");

    buttonPanel.add(close);
    buttonPanel.add(back);
    buttonPanel.add(addCruise);
    buttonPanel.add(removeCruise);

    contentPane.add(buttonPanel);
    Frame1.add(buttonPanel, BorderLayout.SOUTH);

Upon running the code above, all buttons are displayed on the SOUTH of the frame, except the "Close" button. I also want the buttons to span the whole width of the south portion (with no spaces between each buttons) however, I am unsure on how to implement a flow layout, and also use a border layout in order to ensure the buttons are displayed at the bottom.

Is there a way around this?

Upvotes: 0

Views: 144

Answers (2)

dic19
dic19

Reputation: 17971

Upon running the code above, all buttons are displayed on the SOUTH of the frame, except the "Close" button.

Hard to tell why "Close" button is missing without a proper MCVE. Besides be aware that SOUTH constant is discouraged and we should use PAGE_END instead as per standard / internationalization / language orientation trade. From How to Use BorderLayout tutorial:

Before JDK release 1.4, the preferred names for the various areas were different, ranging from points of the compass (for example, BorderLayout.NORTH for the top area) to wordier versions of the constants we use in our examples. The constants our examples use are preferred because they are standard and enable programs to adjust to languages that have different orientations.


I also want the buttons to span the whole width of the south portion (with no spaces between each buttons)

It sounds like a job for GridLayout (link to tutorial) with a single row instead of FowLayout.


I am unsure on how to implement a flow layout, and also use a border layout in order to ensure the buttons are displayed at the bottom.

Your code seems to be close enough but this looks suspicious:

contentPane.add(buttonPanel);
Frame1.add(buttonPanel, BorderLayout.SOUTH);

Don't add a component to different containers. If contentPane is the frame's content pane then the first line is enough. If it's not then the first line is useless.

Upvotes: 1

Adam111p
Adam111p

Reputation: 3717

You have Layout in jFrame. Add new Layout to jPanel too.

Upvotes: 1

Related Questions