Setting header text alignment in JMenu component

Simply put, JMenu.setHorizontalAligment (SwingConstants.CENTER) does nothing, and the text is still left-aligned (using Windows LAF).

Is there a way to align the text in the menu title (and not JMenuItem - JMenus themselves)?

I am using JDK1.7.

What my JMenuBar looks like with its JMenus:

Current JMenuBar with JMenus (and a single JMenuItem

+4
source share
3 answers

I used CSS to place and style the text in the menu. style="text-align:center;" is the CSS used to center text in the example image below. In my case, I encapsulated the JMenu header in the paragraph tags <p> ;

 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:

enter image description here

It is worth noting that in the image above, I also used width:90px;color:blue; in the style attribute, but I removed these two styles from the above code example for simplicity. Hope this helps.

This answer is more or less a copy of my original answer here .

+1
source

Try setHorizontalTextPosition (SwingConstants.CENTER); followed by invalidate ();

+1
source

If you tried to install Margin for the specified JMenu , if I do this:

 JMenu optionsMenu = new JMenu("Option"); optionsMenu.setMargin(new Insets(5, 50, 5, 5)); 

This is the result I get:

MARGIN OUTPUT

MESSENGER IMAGE

+1
source

All Articles