如何为不同的单选按钮定义不同的行为-Java';s SWT
考虑以下代码:如何为不同的单选按钮定义不同的行为-Java';s SWT,java,swt,eclipse-rcp,eclipse-plugin,Java,Swt,Eclipse Rcp,Eclipse Plugin,考虑以下代码: public class SWTTest { public static void main(String[] args) { Display display=new Display(); Shell shell=new Shell(display, SWT.DIALOG_TRIM); Group group=new Group(shell, SWT.SHADOW_ETCHED_OUT); group.
public class SWTTest {
public static void main(String[] args) {
Display display=new Display();
Shell shell=new Shell(display, SWT.DIALOG_TRIM);
Group group=new Group(shell, SWT.SHADOW_ETCHED_OUT);
group.setText("A group");
Button[] options=new Button[2];
options[0]=new Button(group, SWT.RADIO);
options[0].setText("Option 1");
options[0].setLocation(5, 20);
options[0].pack();
options[1]=new Button(group, SWT.RADIO);
options[1].setText("Option 2");
options[1].setLocation(5, 50);
options[1].pack();
options[0].addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
System.out.println("Option 1 Selected");
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
});
group.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
我的意图是,无论何时选择选项1,都会调用widgetSelected(SelectionEvent e)
方法,然后只调用,但问题是选择选项2也会调用widgetSelected(SelectionEvent e)
方法,即使我没有作为侦听器提交选项2,我也没有为它实现widgetSelected(SelectionEvent e)
方法。那么这里发生了什么,我如何为不同的选项选择定义不同的行为呢
编辑 哦。。。还有一件事…
如果我对实现widgetDefaultSelected(SelectionEvent e)方法不感兴趣怎么办?我是否应该这样做?正如爱德华·汤姆森(Edward Thomson)在评论中提到的那样,一个SelectionEvent会在按钮selection及其取消选择按钮上启动 EventListener应检查按钮状态: 我通常是这样做的:
Button button = new Button(parent , SWT.RADIO);
button.addSelectionListener(new SelectionAdapter(){
@override
public void widgetSelected(final SelectionEvent e){
super.widgetSelected();
if(button.getSelection()){
//do your processing
}
}
});
扩展
SelectionAdapter
以获得widgetDefaultSelected
的默认实现。我认为当取消选择某些内容时,您的SelectionListener
也会被触发。您的侦听器应该查询单选按钮的状态,而不是假设事件指示其状态。是的。就这样。改为听鼠标点击。谢谢你们两位的帮助。
Button button = new Button(parent , SWT.RADIO);
button.addSelectionListener(new SelectionAdapter(){
@override
public void widgetSelected(final SelectionEvent e){
super.widgetSelected();
if(button.getSelection()){
//do your processing
}
}
});