9.10. Creating Radio Menu Items

Problem

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

Solution

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

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

See Also

Recipe 9.7 on creating a menu system;

Get Eclipse Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.