Jun 052017

ADM

SWT Button Selection Event

  • 05 June 2017
  • ADM

 

 

 

SWT Button Selection Event - images/logos/eclipse.jpg

 

In SWT, selection events are generated when buttons get selected and pressed. The Selection Events are added to a button using an interface called SelectionListener. There are two methods defined in the SelectionListener interface:

public void widgetSelection(SelectionEvent e)

/** Not applicable to Button */
public void widgetDefaultSelection(SelectionEvent e)

The widgetSelection method is called when a button is selected.

Example

Here is a simple example that changes the text of a label when the button is selected.

package com.admfactory.swt;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

public class ButtonSelectionEventSWT {

    private static int counter = 0;

    public static void main(String[] args) throws Exception {
	final Display display = new Display();
	/** create the new window */
	Shell shell = new Shell(display);

	/** adding the window title */
	shell.setText("Button Selection event examples");

	/** add a layout of 1 columns */
	shell.setLayout(new GridLayout(1, true));

	/** setting up the window size */
	shell.setSize(600, 400);

	/** creating a new label widget on the new created shell */
	final Label label = new Label(shell, SWT.NONE);
	label.setText(counter + "");

	/** creating a new button widget on the new created shell */
	Button button = new Button(shell, SWT.RIGHT);

	button.setText("Click me!");

	/** adding a selection event for the new button */
	button.addSelectionListener(new SelectionListener() {

	    @Override
	    public void widgetSelected(SelectionEvent e) {
		counter++;
		label.setText(counter + "");
	    }

	    @Override
	    public void widgetDefaultSelected(SelectionEvent e) {
		/** Not applicable to Button */
	    }

	});

	/** open the shell/window */
	shell.open();

	/** Loop to keep the application opened */
	while (!shell.isDisposed()) {
	    if (!display.readAndDispatch()) {
		display.sleep();
	    }
	}
	display.dispose();
    }
}

Output

SWT Button Selection Event - /images/SWTButtonEvent01.png

 

 

 

References