问题描述
package test;import org.eclipse.swt.widgets.Display;import org.eclipse.swt.widgets.Shell;import org.eclipse.swt.widgets.Button;import org.eclipse.swt.SWT;import org.eclipse.wb.swt.SWTResourceManager;import org.eclipse.swt.events.SelectionAdapter;import org.eclipse.swt.events.SelectionEvent;public class SWTTest {protected Shell shell;/** * Launch the application. * @param args */public static void main(String[] args) {try {SWTTest window = new SWTTest();window.open();} catch (Exception e) {e.printStackTrace();}}/** * Open the window. */public void open() {Display display = Display.getDefault();createContents();shell.open();shell.layout();while (!shell.isDisposed()) {if (!display.readAndDispatch()) {display.sleep();}}}/** * Create contents of the window. */protected void createContents() {shell = new Shell();shell.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));shell.setSize(450, 300);shell.setText("SWT Application");Button btnA = new Button(shell, SWT.NONE);//为A按钮注册监听器btnA.addSelectionListener(new ButtonClickListener());btnA.setText("A");btnA.setImage(null);btnA.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); btnA.setBounds(30, 51, 76, 56);Button btnB = new Button(shell, SWT.NONE);//为B按钮注册监听器btnB.addSelectionListener(new ButtonClickListener());btnB.setText("B");btnB.setImage(null);btnB.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));btnB.setBounds(129, 51, 76, 56);Button btnC = new Button(shell, SWT.NONE);//为C按钮注册监听器btnC.addSelectionListener(new ButtonClickListener());btnC.setText("C");btnC.setImage(null);btnC.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));btnC.setBounds(240, 51, 76, 56);}private final class ButtonClickListener extends SelectionAdapter {public void widgetSelected(SelectionEvent e) { if(条件1){ //响应按钮A的代码 }else if(条件2){ //响应按钮B的代码 }else if(条件3){ //响应按钮C的代码 }}}} 问题:条件1,条件2,条件3该如何写,才能判断是哪个按钮触发的事件?
解决方案
ButtonClickListener添加一个变量,添加含有该变量的构造方法,在按钮添加监听事件的时候传入参数做为该变量,在事件的if判断中判断该变量的值做不同的操作。