Radio Menu Item Generating SelectionListener twice - SWT
Asked Answered
S

2

6

I have a top level menu named "radio" containing two radio MenuItem. I add SelectionListener for both.

    MenuItem radio = new MenuItem(bar, SWT.CASCADE); /* bar is the menu bar */
    radio.setText("Radio");

    Menu menu = new Menu(radio);
    radio.setMenu(menu);

    MenuItem mntmOption_1 = new MenuItem(menu, SWT.RADIO);
    mntmOption_1.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            System.out.println("Option 1 selected");
        }
    });
    mntmOption_1.setText("Option1");

    MenuItem mntmOption_2 = new MenuItem(menu, SWT.RADIO);
    mntmOption_2.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            System.out.println("Option 2 selected");
        }
    });
    mntmOption_2.setText("Option2");

First I select mntmOption_1 it shows:

Option1 selected

then I select mntmOption_2 it shows:

Option1 selected
Option2 selected

It seems it is firing both listeners. here is the question: Why? I'm running WinXP.

Shing answered 6/12, 2011 at 9:40 Comment(0)
L
10

It is firing both listeners, since the second radio button looses its selection. You should check widget state, if you want to react only to a particular state.

Lucarne answered 6/12, 2011 at 12:29 Comment(0)
Y
3

While implementing, I came across swt radio button trigger double eventlistener for select and deselect problem.

To solve issue add:

        boolean isSelected = ((Button)e.getSource()).getSelection();
        if(isSelected){ 
            ....                   
        }

Example:

buttonRd0 = new Button(parent, SWT.RADIO);
button.addSelectionListener(new SelectionAdapter() {
     @Override
     public void widgetSelected(SelectionEvent e)
     {
        boolean isSelected = ((Button)e.getSource()).getSelection();
        if(isSelected){ 
            ....                   
        }
     }
 });
Ylem answered 1/4, 2016 at 20:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.