[SWT] Button handles the selection and deselection events of the Checkbox button

introduce:

When using Java SWT (Standard Widget Toolkit) to create a graphical user interface, you often need to handle button selection and deselection events. This article will introduce how to implement the processing of button selection and deselection events by adding a SelectionListener listener, and modify the values ​​of related variables accordingly.

Sample code:


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

public class CheckboxExample {
    
    
	private boolean checked = false;

	public static void main(String[] args) {
    
    
		Display display = new Display();
		Shell shell = new Shell(display);
		shell.setLayout(new GridLayout());
		shell.setMinimumSize(360, 360);
		shell.setText("Checkbox Example");

		CheckboxExample example = new CheckboxExample();
		example.createCheckbox(shell);

		shell.pack();
		shell.open();

		while (!shell.isDisposed()) {
    
    
			if (!display.readAndDispatch()) {
    
    
				display.sleep();
			}
		}

		display.dispose();
	}

	private void createCheckbox(Shell shell) {
    
    
		Composite cmp = new Composite(shell, SWT.NONE);
		cmp.setLayout(new GridLayout());
		cmp.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.CENTER));
		
		Button ckBox = new Button(cmp, SWT.CHECK);
		ckBox.setText("Check me");
		ckBox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.CENTER));

		Label label = new Label(cmp, SWT.NONE);
		label.setText("value: " + ckBox.getSelection());
		label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.CENTER));

		ckBox.addSelectionListener(new SelectionAdapter() {
    
    
			@Override
			public void widgetSelected(SelectionEvent e) {
    
    
				Button button = (Button) e.widget;
				checked = button.getSelection();
				label.setText("value: " + checked);
			}
		});
	}
}

Effect

When not selected
insert image description here

When selected,
insert image description here
animation:
insert image description here

Summary:
By adding a SelectionListener listener, you can easily handle SWT button selection and deselection events. In the sample code, we create a checkbox button and assign its checked status to a Boolean variable checked. Then use Label to echo the CheckBox status to the interface. In the example, the value of the Checkbox is processed through the callback method in the listener, and further processing can also be performed, such as printing the selected status or performing other related operations.

Guess you like

Origin blog.csdn.net/m0_47406832/article/details/132744068