< Day Day Up > |
Recipe 8.7 Handling SWT Widget Events8.7.1 ProblemYou need to catch widget events such as button clicks and respond to them in code. 8.7.2 SolutionUse an SWT listener. In SWT, listeners are much like listeners in AWT. Here are some of the most popular SWT listeners:
8.7.3 DiscussionTo see how this works, we'll continue the example begun in the previous recipe where we want text to appear in a text widget when you click a button. You can catch button clicks by adding a SelectionListener object to the button with the addSelectionListener method. To implement the SelectionListener interface, you have to implement two methods: widgetSelected, which occurs when a selection occurs in a widget, and widgetDefaultSelected, which occurs when a default selection is made in a widget. In this case, we're going to display the text No problem in the text widget using a SelectionListener object in an anonymous inner class: public class ButtonClass { public static void main(String [] args) { Display display = new Display( ); Shell shell = new Shell(display); shell.setSize(200, 200); shell.setText("Button Example"); final Button button = new Button(shell, SWT.PUSH); button.setBounds(40, 50, 50, 20); button.setText("Click Me"); final Text text = new Text(shell, SWT.BORDER); text.setBounds(100, 50, 70, 20); button.addSelectionListener(new SelectionListener( ) { public void widgetSelected(SelectionEvent event) { text.setText("No problem"); } public void widgetDefaultSelected(SelectionEvent event) { text.setText("No worries!"); } }); . . .
All you need to complete this example is the code to close the shell when needed (see Example 8-5). Example 8-5. Using SWT buttons and text widgetspackage org.cookbook.ch08;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
public class ButtonClass {
public static void main(String [] args) {
Display display = new Display( );
Shell shell = new Shell(display);
shell.setSize(200, 200);
shell.setText("Button Example");
final Button button = new Button(shell, SWT.PUSH);
button.setBounds(40, 50, 50, 20);
button.setText("Click Me");
final Text text = new Text(shell, SWT.BORDER);
text.setBounds(100, 50, 70, 20);
button.addSelectionListener(new SelectionListener( )
{
public void widgetSelected(SelectionEvent event)
{
text.setText("No problem");
}
public void widgetDefaultSelected(SelectionEvent event)
{
text.setText("No worries!");
}
});
shell.open( );
while(!shell.isDisposed( )) {
if(!display.readAndDispatch( )) display.sleep( );
}
display.dispose( );
}
} The results appear in Figure 8-6; when you click the button, the text message No problem appears in the text widget. Figure 8-6. Using buttons and text widgets8.7.4 See AlsoRecipe 8.1 on using widgets in SWT; Recipe 8.6 on creating button and text widgets. |
< Day Day Up > |