Java Tips Weblog

  • Blog Stats

    • 2,614,742 hits
  • Categories

  • Archives

Popup Menu Alignment

Posted by Rob Camick on December 3, 2008

A JPopupMenu displays JMenuItems with the text left aligned. In fact the popup menu goes to a lot of trouble to make sure the text of each menu item is properly aligned. For example, if you try using the setIconTextGap() method on a single menu item, that gap is used for all menu items. This makes it difficult to change the text alignment to be centered or right aligned if you have a reason to do so.

The only solution I can find, without rewriting the UI, is a brute force solution. That is, change the text of the menu item to contain spaces to give the appearance of a custom alignment. The PopupMenuAlignment class does the brute force work for you. It will support two different alignment options:

  • Center – text is aligned to the center of the space available
  • Trailing – text is aligned to the trailing edge of the menu item. Assuming the default ComponentOrientation of left to right, this would be the right edge.

The PopupMenuAlignment class can be used in two ways:

  • Statically – used when all the menu items are known at design time
  • Dynamically – used when the menu items may change at run time

To invoke the class statically the code would look something like:

JMenu menu= new JMenu("Trailing");
menu.add(...);
menu.add(...);
PopupMenuAlignment.alignText(
menu.getPopupMenu(), PopupMenuAlignment.TRAILING);

To invoke the class dynamically the code would look something like:

JMenu menu= new JMenu("Center");
menu.getPopupMenu().addContainerListener(
new PopupMenuAlignment(PopupMenuAlignment.CENTER));
menu.add(...);
menu.add(...);

Using the code above for center alignment the popup menu would look like…

popup-menu-alignment

Get The Code

PopupMenuAlignment.java

Leave a comment

 
Design a site like this with WordPress.com
Get started