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?
Asked
Active
Viewed 3,840 times
1

Andrew Thompson
- 168,117
- 40
- 217
- 433

zbz.lvlv
- 3,597
- 6
- 34
- 38
3 Answers
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.

Community
- 1
- 1

Andrew Thompson
- 168,117
- 40
- 217
- 433
-
@camickr Yes, it is the type of one-liner 'add as single component with no constraint' that I especially like. – Andrew Thompson May 24 '13 at 04:23
-
@Craig Yes, at just 55 LOC, it is one of my favorite SSCCEs. :) – Andrew Thompson May 24 '13 at 05:21
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
-
1But 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