Event
handlers are used to get notification when particular events happened on SWT
widget.
Ex:
button1.addSelectionListener(new
SelectionAdapter() {
public void
widgetSelected(SelectionEvent e) {
System.out.println("Submit
button was clicked");
}
});
package swt_app; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class Test { private static int xPosition = 30; private static int yPosition = 30; private static int width = 500; private static int height = 30; private static int scrollWidth = 500; private static int scrollHeight = 350; private static int shellWidth = 600; private static int shellHeight = 600; private static void addWidgetsToShell(Shell shell) { Text text1 = new Text(shell, SWT.BORDER); text1.setText("You can't edit me"); text1.setBounds(xPosition, yPosition, width, height); text1.setEditable(false); yPosition += 40; Text text2 = new Text(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); text2.setText("Bordered scrolled text box"); text2.setBounds(xPosition, yPosition, scrollWidth, scrollHeight); yPosition += 80; Button button1 = new Button(shell, SWT.PUSH); button1.setText("Submit"); button1.setLocation(xPosition + 130, yPosition + 300); button1.setSize(100, 20); Button button2 = new Button(shell, SWT.PUSH); button2.setText("Cancel"); button2.setLocation(xPosition + 260, yPosition + 300); button2.setSize(100, 20); button1.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { System.out.println("Submit button was clicked"); } }); button2.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { System.out.println("Cancel button was clicked"); } }); } public static void main(String[] args) { /* Instantiate Display object, it represents SWT session */ Display display = new Display(); /* * Define Shell, it represent a window, You can add more than one shell * to Display */ Shell shell = new Shell(display); shell.setSize(shellWidth, shellHeight); addWidgetsToShell(shell); /* Open shell window */ shell.open(); /* * Run the event dispatching loop until an exit condition occurs, which * is typically when the main shell window is closed by the user. */ while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } /* Dispose the display */ display.dispose(); } }
Experiment
by clicking Submit, Cancel buttons, you can able to see the messages in
console.
No comments:
Post a Comment