Java Reference
In-Depth Information
If you want a vertical menu bar, instead of a horizontal one, simply change the
LayoutManager
of the menu bar component. A setup such as a 0 row by 1 column
GridLayout
does the job, as
shown in the following example, because the number of rows will grow infinitely for each
JMenu
added:
import java.awt.*;
import javax.swing.*;
public class VerticalMenuBar extends JMenuBar {
private static final LayoutManager grid = new GridLayout(0,1);
public VerticalMenuBar() {
setLayout(grid);
}
}
Moving the menu bar shown in Figure 6-1 to the east side of a
BorderLayout
and making it
a
VerticalMenuBar
instead of a
JMenuBar
produces the setup shown in Figure 6-4. Although the
vertical menu bar may look a little unconventional here, it's more desirable to have menu items
appearing stacked vertically, rather than horizontally, on the right (or left) side of a window. You
may, however, want to change the
MenuBar.border
property to a more appropriate border.
Figure 6-4.
Using the VerticalMenuBar
■
Note
Changing the layout manager of the
JMenuBar
has one negative side effect: Because top-level menus
are pull-down menus, open menus on a vertical bar will obscure the menu bar. If you want to correct this pop-
up placement behavior, you must extend the
JMenu
class and override its protected
getPopupMenuOrigin()
method in order to make the pop-up menu span out, rather than drop down.
SingleSelectionModel Interface
The
SingleSelectionModel
interface describes an index into an integer-indexed data structure
where an element can be selected. The data structure behind the interface facade is most likely
an array or vector in which repeatedly accessing the same position is guaranteed to return the
same object. The
SingleSelectionModel
interface is the selection model for a
JMenuBar
as well
as a
JPopupMenu
. In the case of a
JMenuBar
, the interface describes the currently selected
JMenu
that needs to be painted. In the case of a
JPopupMenu
, the interface describes the currently
selected
JMenuItem
.