danglingPointer
danglingPointer

Reputation: 916

Component inside JMenuBar wants to align far right after JSeparator?

Take a look at this image:

enter image description here

As you can see, I have a JSeparator between my "Auto Refreshing" JCheckBox and my "Show Column" menu, and my "Show Column" menu is wanting to be as far right as possible. Why is it not aligning itself to the left, like everything else before the JSeparator? And I can't seem to make it do so, here is my current code:

JCheckBox pulling = new JCheckBox("Auto Refreshing");
...
menuBar.add(pulling);

menuBar.add(new javax.swing.JSeparator(javax.swing.SwingConstants.VERTICAL));

JMenu showMenu = new JMenu("Show Column");
showMenu.setAlignmentX(Component.LEFT_ALIGNMENT);
menuBar.add(showMenu);

Upvotes: 1

Views: 456

Answers (2)

danglingPointer
danglingPointer

Reputation: 916

The issue was the size of the JSeparator, it wanted to take up as much horizontal space as possible. So, my solution was to restrict it's size so that it could only be one pixel wide max:

JSeparator menuSep = new JSeparator(javax.swing.SwingConstants.VERTICAL);
menuSep.setMaximumSize(new java.awt.Dimension(1, 1000));
menuBar.add(menuSep);

Upvotes: 0

milez
milez

Reputation: 2201

This tutorial might be helpful. A quote:

By default, most components have center X and Y alignment. However, buttons, combo boxes, labels, and menu items have a different default X alignment value: LEFT_ALIGNMENT.

So you can see that placement logic differs, in other words, don't count on it. However, I do not know why your manual alignment to left did not work. Most likely the problem is the size of your last menu. What you can do, is use glue as filler since JMenuBar has a BoxLayout.

menuBar.add(showMenu);
menuBar.add(Box.createHorizontalGlue());

This invisible space will be added to the end of your menu and it will push components before it the left.

Upvotes: 2

Related Questions