javaswtmenuitem

Radio Menu Item Generating SelectionListener twice - SWT


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.


Solution

  • 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.