< Day Day Up > |
Recipe 8.6 Creating Button and Text Widgets8.6.1 ProblemYou need to use buttons to interact with the user and to display text in your application. 8.6.2 SolutionUse SWT button and text widgets and use SWT listeners to catch button events. 8.6.3 DiscussionThis example adds SWT button widgets to a shell and catches click events, displaying a message in a text widget when the button is clicked. We'll start by creating a button widget in a new project, ButtonApp. Here's a selection of some of the most popular button widget methods:
Creating button widgets is easy enough; just use the Button class's constructor, position the button with setBounds or a layout, and set the caption in the button with the setText method: package 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"); . . . Creating a text widget is similarly easy. Here's a selection of popular text widget methods:
In this example, we'll give this text widget a border and add it to our shell: 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); . . . That installs the button and text widgets; the next step is to handle button events, which we'll discuss in the next recipe. 8.6.4 See AlsoRecipe 8.1 on using widgets in SWT; Recipe 8.7 on handling events from widgets; Chapter 7 of Eclipse (O'Reilly). |
< Day Day Up > |