Grammin
Grammin

Reputation: 12205

JSeparator not in the right place in my JPanel

So my code is as follows:

JPanel mainPanel = new JPanel();

mainPanel.setBorder(new EmptyBorder(50,50,0,10));

BoxLayout layout = new BoxLayout(mainPanel, BoxLayout.Y_AXIS);
mainPanel.setLayout(layout);

JSeparator separate = new JSeparator(SwingConstants.HORIZONTAL);
mainPanel.add(separate);

mainPanel.add(new JButton());
mainPanel.add(new JButton());

the problem that I keep having is that instead of my panel looking like:

______________
|             |
|  ------     |
|  Button     |
|  Button     |
|             |
|             |
|             |
______________

it for some reason puts a ton of space in between the buttons and separator so it looks like:

______________
|             |
|  ------     |
|             |
|             |
|             |
|  Button     |
|  Button     |
______________

For the life of me I can't get the buttons to be next to the JSeparator, any ideas?

Upvotes: 2

Views: 2946

Answers (2)

camickr
camickr

Reputation: 324137

BoxLayout respects the maximum size of the component. When there is more space available the component will grow to take up the extra space. You need to prevent the separator from growing:

JSeparator separate = new JSeparator(SwingConstants.HORIZONTAL);
System.out.println(separate.getPreferredSize());
System.out.println(separate.getMaximumSize());
Dimension d = separate.getPreferredSize();
d.width = separate.getMaximumSize().width;
separate.setMaximumSize( d );

Upvotes: 5

Jeffrey
Jeffrey

Reputation: 44808

If the the Y alignments (from .getAlignmentY()) aren't the same, BoxLayout tends to do funky things. Try manually setting the alignments to the top. (Same thing happens with the X alignment in BoxLayout.)

Upvotes: 0

Related Questions