8.7. Handling SWT Widget Events
Problem
You need to catch widget events such as button clicks and respond to them in code.
Solution
Use an SWT listener. In SWT, listeners are much like listeners in AWT. Here are some of the most popular SWT listeners:
-
ControlListener Handles moving and resizing events
-
FocusListener Handles getting and losing focus events
-
KeyListener Handles keystroke events
-
MouseListener,MouseMoveListener,MouseTrackListener Handles mouse events
-
SelectionListener Handles widget selection events (including button clicks)
Discussion
To 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 ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access