JMenuBar 中的组件想要在 JSeparator 之后最右边对齐?

Component inside JMenuBar wants to align far right after JSeparator?

看看这张图片:

如您所见,我的 "Auto Refreshing" JCheckBox 和 "Show Column" 菜单之间有一个 JSeparator,我的 "Show Column" 菜单希望尽可能靠右。为什么它不向左对齐,就像 JSeparator 之前的其他所有内容一样?我似乎无法做到这一点,这是我当前的代码:

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);

这个 tutorial 可能会有帮助。引述:

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.

所以你可以看到放置逻辑不同,换句话说,不要指望它。但是,我不知道为什么您的手动左对齐不起作用。问题很可能是上一个菜单的大小。你可以做的是使用 glue as filler 因为 JMenuBar 有一个 BoxLayout.

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

这个不可见的 space 将被添加到您的菜单的末尾,它会将它前面的组件推到左边。

问题在于 JSeparator 的大小,它希望在水平方向上占据尽可能多的空间 space。所以,我的解决方案是限制它的大小,使其最大只能是一个像素宽:

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