1

How to add a JButton into the center of a JFrame with BorderLayout()? I tried using BorderLayout.CENTER, but instead of the center of the screen, it gave the top-center of the screen. Or do I have to use another layout manager?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
zbz.lvlv
  • 3,597
  • 6
  • 34
  • 38

3 Answers3

5

Put a JPanel in the CENTER and set the layout to GridBagLayout or BoxLayout as seen in this answer to Set component at center of the page.

The GridBagLayout is used to center a label containing the yellow/red gradient image seen in the Nested Layout Example.

Animated image of nested layout example showing size change

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

It may take some time to learn, but SpringLayout is worth looking into. It will let you position elements on the GUI where you wish. You can look here for examples of different layouts.

Aaron
  • 992
  • 3
  • 15
  • 33
0

try this

frame.getContentPane().setLayout(new BorderLayout(0, 0));

JButton btnNewButton = new JButton("New button");
frame.getContentPane().add(btnNewButton, BorderLayout.CENTER);
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
Sanjaya Liyanage
  • 4,706
  • 9
  • 36
  • 50
  • 1
    But that will stretch the component (in this case a `JButton`) to the size of the container as seen in the screenshot below. This use-case sounds more like 'center with white space around component'. – Andrew Thompson May 24 '13 at 04:25
  • *"as seen in the screenshot.."* ..in my [answer](http://stackoverflow.com/a/16727593/418556). – Andrew Thompson May 24 '13 at 04:45