DekGenius.com
Previous Section  < Day Day Up >  Next Section

Recipe 9.10 Creating Radio Menu Items

9.10.1 Problem

You want to add "selectable" menu items to a menu that, when selected, stay selected until another selectable item is selected instead.

9.10.2 Solution

Use SWT radio menu items, created by setting a MenuItem object's style to SWT.RADIO.

9.10.3 Discussion

For example, say that you want to add two radio items to the File menu in the menu example developed earlier in this chapter. You want those radio items to set the language used in the application to either German or English. You can create two new SWT.RADIO menu items in this way:

fileEnglishItem = new MenuItem(fileMenu, SWT.RADIO);
fileEnglishItem.setText("English");

fileGermanItem = new MenuItem(fileMenu, SWT.RADIO);
fileGermanItem.setText("German");

To handle their events, we'll create a class named RadioItemListener, which extends the SelectionAdapter class. Here we're going to catch whichever radio menu item was selected and report which language is in use (if you specifically want to check if a menu item's radio button is selected, call its getSelection method):

class RadioItemListener extends SelectionAdapter
{
    public void widgetSelected(SelectionEvent event)
    {
       MenuItem item = (MenuItem)event.widget;
       text.setText(item.getText( ) + " is on.");
    }
}

The results appear in Figure 9-8, where you can see the German and English radio menu items. As you select one or the other of these items, SWT toggles their radio buttons on and off.

Figure 9-8. Radio menu items
figs/ecb_0908.gif


9.10.4 See Also

Recipe 9.7 on creating a menu system; Recipe 9.8 on creating text menu items; Recipe 9.9 on creating image menu items; Recipe 9.11 on creating menu item accelerators and mnemonics; Recipe 9.12 on enabling and disabling menu items.

    Previous Section  < Day Day Up >  Next Section