public class MultipleListenersExample implements HelpListener, VerifyListener, ModifyListener { private static final double FIVE_NINTHS = 5.0 / 9.0; private static final double NINE_FIFTHS = 9.0 / 5.0; private Text fahrenheit; private Text celsius; private Label help; public void run() { Display display = new Display(); Shell shell = new Shell(display); shell.setText("Temperatures"); createContents(shell); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } display.dispose(); } private void createContents(Shell shell) { shell.setLayout(new GridLayout(3, true)); new Label(shell, SWT.LEFT).setText("Fahrenheit:"); fahrenheit = new Text(shell, SWT.BORDER); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalSpan = 2; fahrenheit.setLayoutData(data); fahrenheit.setData("Type a temperature in Fahrenheit"); // 为华氏温度文本框添加监听器 fahrenheit.addHelpListener(this); fahrenheit.addVerifyListener(this); fahrenheit.addModifyListener(this); new Label(shell, SWT.LEFT).setText("Celsius:"); celsius = new Text(shell, SWT.BORDER); data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalSpan = 2; celsius.setLayoutData(data); celsius.setData("Type a temperature in Celsius"); //为摄氏温度文本框添加监听器 celsius.addHelpListener(this); celsius.addVerifyListener(this); celsius.addModifyListener(this); help = new Label(shell, SWT.LEFT | SWT.BORDER); data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalSpan = 3; help.setLayoutData(data); } //响应帮助事件 public void helpRequested(HelpEvent event) { help.setText((String) event.widget.getData()); } //响应校验事件 public void verifyText(VerifyEvent event) { event.doit = false; char myChar = event.character; String text = ((Text) event.widget).getText(); if (myChar == '-' && text.length() == 0) event.doit = true; if (Character.isDigit(myChar)) event.doit = true; if (myChar == '\b') event.doit = true; } //响应文本修改的事件 public void modifyText(ModifyEvent event) { // 删除监听器,从而在modifyText过程中不会触发事件 celsius.removeVerifyListener(this); celsius.removeModifyListener(this); fahrenheit.removeVerifyListener(this); fahrenheit.removeModifyListener(this); Text text = (Text) event.widget; try { int temp = Integer.parseInt(text.getText()); if (text == fahrenheit) { celsius.setText(String.valueOf((int) (FIVE_NINTHS * (temp - 32)))); } else { fahrenheit.setText(String.valueOf((int) (NINE_FIFTHS * temp + 32))); } } catch (NumberFormatException e) { /* Ignore */ } //添加监听器 celsius.addVerifyListener(this); celsius.addModifyListener(this); fahrenheit.addVerifyListener(this); fahrenheit.addModifyListener(this); } public static void main(String[] args) { new MultipleListenersExample().run(); } }
程序运行效果如图4所示。

图4 文本监听器
提示:一般来说,监听器都有一个抽象的Adaper类实现监听器的方法,例如FocusAdapter实现了FocusListener的方法(方法为空)。如果读者不想实现监听器的全部方法则可以继承监听器的Adaper类,否则要实现监听器接口的所有方法。