Determining Whether a Check or Radio Button Is Selected

If you use CHECK- or RADIO-style toolbar items, at some point you must perform a check in your code to determine the current state of the button

How do I do that?

In a SelectionListener--or any other block of code—you can determine whether a check or radio item is selected by calling the ToolItem getSelection( ) method.:

Note

CHECK- and RADIO-style menu items work the same way, so the code required to determine status is similar.

checkItem.addSelectionListener(new SelectionListener( ) {
      public void widgetSelected(SelectionEvent event) {
          if(checkItem.getSelection( ))
          {    
              System.out.println("Check");
          }
          else
          {
              System.out.println("Uncheck");
          }                   
      }
      public void widgetDefaultSelected(SelectionEvent event)
      {
      }
});

The code you develop for the widgetSelected( ) method depends upon the application. In place of the call to System.out.println( ), you could set a boolean instance variable that could be used to govern other program logical flow. Or you could define all tool items at the class level and call getSelection( ) whenever needed.

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.