问题
Simply put, JMenu.setHorizontalAligment(SwingConstants.CENTER) does nothing and the text is still left-aligned (using the Windows LAF).
Is there any method of aligning the text in a menu header (not the JMenuItem - the JMenus themselves)?
I'm using JDK1.7.
What my JMenuBar with its JMenus looks like currently:

回答1:
I've used CSS
to position and style the text in the menus. style="text-align:center;"
is the CSS
used to position the text in the center in the example image at the bottom. In my case, I encapsulated the JMenu
title in <p>
paragraph tags;
clientFilter = new JMenu("<html><p style='text-align:center;'>Client</p></html>");
siteFilter = new JMenu("<html><p style='text-align:center;'>Site</p></html>");
employeeFilter = new JMenu("<html><p style='text-align:center;'>Employee</p></html>");
jobtypeFilter = new JMenu("<html><p style='text-align:center;'>Job Type</p></html>");
Which looks like this;

It's worth noting that in the image above I have also used width:90px;color:blue;
in the style attribute, but I removed those two styles from the code example above for simplicity. Hope this helps.
This answer is more or less a copy of my original answer here.
回答2:
Try setHorizontalTextPosition(SwingConstants.CENTER); followed by invalidate();
回答3:
Had you tried setting Margin for the said JMenu
, if I do this :
JMenu optionsMenu = new JMenu("Option");
optionsMenu.setMargin(new Insets(5, 50, 5, 5));
This is the output I get :


来源:https://stackoverflow.com/questions/11712667/setting-alignment-of-title-text-in-a-jmenu-component