Most graphical application makes use of some sort of menu. Its labels are often referred to as File, Edit, or Exit, for instance, and are usually placed on the top of an application window to display a list of choices. In SWT, the Menu
and MenuItem
classes are responsible for handling operations related to menus.
Basically, we can divide menus into three different kinds:
SWT.BAR
style below the shell titleSWT.DROP_DOWN
styleSWT_POP_UP
style and are displayed when an user requests a menu in a controlThe relationship among these three types of menus works by having the menu bars and pop-up menus as the root of the hierarchy. Both of them are usually composed of drop-down menus.
Menu acts as a container for MenuItems
, and contains methods so that MenuItems
can be added. MenuItem
is a widget that can be selected by the user or can display another menu. It can be divided into the following categories:
SWT.PUSH
: A standard menu item is created in this categorySWT.CHECK
: It is used for a checkbox buttonSWT.RADIO
: It is used for a radio buttonSWT.SEPARATOR
: It is used to separate several menu itemsSWT.CASCADE
: It is used to create a submenu in a cascade styleThere are several events that can be triggered from a Menu
object and a MenuItem
object:
The following snippet of code shows an example of how to use a Menu
object and a MenuItem
object. Their implementation is quite straightforward. Notice that the MenuItem
object is created using the Menu
object as basis.
... Display display = new Display(); Shell shell = new Shell(display); Menu menuBar = new Menu(shell, SWT.BAR); shell.setMenuBar(menuBar); MenuItem fileItem = new MenuItem(menuBar, SWT.CASCADE); fileItem.setText("File"); MenuItem editItem = new MenuItem(menuBar, SWT.CASCADE); editItem.setText("Edit"); Menu fileMenu = new Menu(shell, SWT.DROP_DOWN); fileItem.setMenu(fileMenu); String [] fileStrings = {"New", "Exit"}; for (int i=0; i<fileStrings.length; i++) { MenuItem item = new MenuItem(fileMenu, SWT.PUSH); item.setText(fileStrings [i]); } Menu editMenu = new Menu(shell, SWT.DROP_DOWN); String [] editStrings = {"Copy", "Paste"}; editItem.setMenu(editMenu); for (int i=0; i<editStrings.length; i++) { MenuItem item = new MenuItem(editMenu, SWT.PUSH); item.setText(editStrings [i]); } shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); …
The following screenshot shows the corresponding graphical output: