Java Tips Weblog

  • Blog Stats

    • 1,759,029 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.getPopupMenu(), PopupMenuAlignment.TRAILING);

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

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

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


Get The Code

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: