Posted by Darryl Burke on February 1, 2009
New: keepVisible(JMenuItem) and keepVisible(int) methods scroll the menu to the specified item or index.
A drawback of the JMenu API is that it does not provide a method to limit the number of items displayed at a time, something on the lines of the JComboBox method setMaximumRowCount. This means that adding a large number of items to a menu can and does result in a menu too tall for the screen. The usual workaround is to nest the items in submenus, which can make it tedious for the user to find and select the desired item, and lead to quite some extra code for the programmer, especially if the menu items are added dynamically at run time.
MenuScroller addresses this shortcoming by deterministically adding up and down arrows to the top and bottom of the menu. A number of items can optionally be frozen at the top and/or bottom of a scrolling subset of menu items.
There are two ways in which a MenuScroller can be attached to a JMenu/JPopupMenu. The recommended method, which provides better readability for your code, is via a call to the class’s static method
public static MenuScroller
int topFixedCount, int bottomFixedCount]]]);
where the square brackets [ ] indicate optional parameters.
As a glance at the code will show, it is also sufficient to construct a MenuScroller with the JMenu/JPopupMenu as the first (or only) parameter.
This illustration shows the MenuScroller in action. The line of code to set this scroller was
MenuScroller.setScrollerFor(menu, 8, 125, 3, 1);
If a reference to the MenuScroller is retained, the number of items to scroll, the scrolling interval in milliseconds and the number of items to freeze at the top or bottom can be retrieved and set via the accessors and mutators provided. An item or an index into the menu can also be specified to be made visible whenever the menu is shown.
To restore the default, non-scrolling behavior of the JMenu, invoke the MenuScroller‘s dispose() method.
Try The Demo
Get The Code
The Java™ Tutorials: