Softey
Softey

Reputation: 1491

JFrame and JPanel centering

I was wondering how would I add a JPanel to a JFrame and make sure it is centered and had a gap of set size on either sides? I can get it in the center but it sticks to the edge.

Upvotes: 2

Views: 138

Answers (1)

Paul C
Paul C

Reputation: 8457

use a Border layout. Put the JPanel in the center, then use Box.createHorizontalStrut(size) and Box.createVerticalStrut(size) in the east/west and north/south locations, respectively.

something like: (from memory, might not be exactly right)

JPanel panel = new JPanel();
int gap = 20;  //or whatever
frame.getContentFrame().setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
panel.add(Box.createHorizontalStrut(gap), BorderLayout.EAST);
panel.add(Box.createHorizontalStrut(gap), BorderLayout.WEST);
panel.add(Box.createVerticalStrut(gap), BorderLayout.NORTH);
panel.add(Box.createVerticalStrut(gap), BorderLayout.SOUTH);

Upvotes: 5

Related Questions