Setting alignment of title text in a JMenu component

拥有回忆 提交于 2019-12-10 16:27:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!