Determining the State of CHECK and RADIO Menu Items

When you add a Listener to a menu item with the SWT.CHECK or SWT.RADIO style, you need to take extra steps to determine the state of the item. After all, it is the state of the item that controls what action you take in your code.

How do I do that?

You add a Listener to a CHECK or RADIO menu item in exactly the same manner as you do for a regular menu item. The difference comes in what code you write in the widgetSelected( ) method for your Listener. Specifically, the action you take will depend upon the state of the menu item (whether checked or unchecked). SWT provides a method to use to determine the menu’s state. A typical Listener looks like this:

checkItem.addSelectionListener(new SelectionListener( ) { public void widgetSelected(SelectionEvent e) { if(checkItem.getSelection( )) { System.out.println("Check Menu was Checked"); } else { System.out.println("Check Menu was Un-Checked"); } } public void widgetDefaultSelected(SelectionEvent e) { } }); radioItem1.addSelectionListener(new SelectionListener( ) { public void widgetSelected(SelectionEvent e) { if(radioItem1.getSelection( )) { System.out.println("Radio One was Checked"); } } public void widgetDefaultSelected(SelectionEvent e) { } }); radioItem2.addSelectionListener(new SelectionListener( ) { public void widgetSelected(SelectionEvent e) { if(radioItem2.getSelection( )) { System.out.println("Radio Two was Checked"); } } public void widgetDefaultSelected(SelectionEvent e) ...

Get SWT: A Developer's Notebook 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.