< Day Day Up > |
Recipe 9.7 Creating a Menu System9.7.1 ProblemYou want to create and add a menu system to your SWT application. 9.7.2 SolutionCreate a menu system with Menu and MenuItem objects. You create a new Menu object for the menu system itself, and new MenuItem objects for the individual menus and menu items. 9.7.3 DiscussionYou use Menu and MenuItem objects to create menu systems in SWT; to get a handle on this process, we're going to create a menu system here, with File and Edit menus. When the user selects a menu item we'll display the item he has selected in a text widget. This example is MenuApp at this book's site. You start by creating a standard menu system with a Menu object corresponding to the menu bar. Here is a selection of popular Menu methods:
Here's our menu bar, created with the SWT.BAR style: public class MenuClass
{
Display display;
Shell shell;
Menu menuBar;
Text text;
public MenuClass( )
{
display = new Display( );
shell = new Shell(display);
shell.setText("Menu Example");
shell.setSize(300, 200);
text = new Text(shell, SWT.BORDER);
text.setBounds(80, 50, 150, 25);
menuBar = new Menu(shell, SWT.BAR);
.
.
. After creating an object corresponding to the menu bar, you create menu items in the menu bar such as the File and Edit menu. However, you don't use the Menu class; you use the MenuItem class. The following is a selection of popular MenuItem methods.
Here's how to create a File menu header, giving it the caption File and the mnemonic F (which means the menu also can be opened by pressing, for example, Alt-F in Windows or Apple-F in Mac OS X): public class MenuClass { Display display; Shell shell; Menu menuBar; MenuItem fileMenuHeader; Text text; public MenuClass( ) { display = new Display( ); shell = new Shell(display); shell.setText("Menu Example"); shell.setSize(300, 200); text = new Text(shell, SWT.BORDER); text.setBounds(80, 50, 150, 25); menuBar = new Menu(shell, SWT.BAR); fileMenuHeader = new MenuItem(menuBar, SWT.CASCADE); fileMenuHeader.setText("&File"); . . . To create the actual drop-down File menu, use the Menu class with the SWT.DROP_DOWN style, and add that new menu to the File menu header like so: public class MenuClass { Display display; Shell shell; Menu menuBar, fileMenu; MenuItem fileMenuHeader; Text text; public MenuClass( ) { . . . menuBar = new Menu(shell, SWT.BAR); fileMenuHeader = new MenuItem(menuBar, SWT.CASCADE); fileMenuHeader.setText("&File"); fileMenu = new Menu(shell, SWT.DROP_DOWN); fileMenuHeader.setMenu(fileMenu); . . . This gives you a File menu, as shown in Figure 9-5. How do you add items to this menu? See the next recipe. Figure 9-5. A File menu9.7.4 See AlsoRecipe 9.8 on creating text menu items; Recipe 9.9 on creating image menu items; Recipe 9.10 on creating radio menu items; Recipe 9.11 on creating menu item accelerators and mnemonics; Recipe 9.12 on enabling and disabling menu items; Chapter 8 in Eclipse (O'Reilly). |
< Day Day Up > |