8.6. Creating Button and Text Widgets

Problem

You need to use buttons to interact with the user and to display text in your application.

Solution

Use SWT button and text widgets and use SWT listeners to catch button events.

Discussion

This 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:

void addSelectionListener(SelectionListener listener)

Adds the listener to the collection of listeners who will be notified when the button is selected

String getText( )

Returns the button’s text

void setBounds(int x, int y, int width, int height)

Sets the button’s size and location to the area specified by the arguments

void setImage(Image image)

Sets the button’s image

void setText(String string)

Sets the button’s text

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, ...

Get Eclipse Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.