Radio menu item. Generation SelectionListener twice - SWT

I have a top-level menu with the name "radio" containing two Radio MenuItem . I add a 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 

He seems to be shooting at both listeners. here is the question: why? I am running WinXP.

+4
source share
2 answers

It starts both listeners as the second radio button loses its choice. You must check the state of the widget if you want to respond only to a specific state.

+8
source

During implementation, I came across a swt radio button trigger double eventlistener to select and deselect.

To solve the problem, 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){ .... } } }); 
+1
source

Source: https://habr.com/ru/post/1384869/


All Articles