ColorDialogButtonActionSetLabelBackground.java Source code

Java tutorial

Introduction

Here is the source code for ColorDialogButtonActionSetLabelBackground.java

Source

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

public class ColorDialogButtonActionSetLabelBackground {

    public static void main(String[] args) {
        Display display = new Display();
        final Shell shell = new Shell(display);
        shell.setText("Color Chooser");
        shell.setLayout(new GridLayout(2, false));

        final Label colorLabel = new Label(shell, SWT.NONE);
        colorLabel.setText("Color");

        Button button = new Button(shell, SWT.PUSH);
        button.setText("Color...");
        button.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent event) {
                Color color = new Color(shell.getDisplay(), new RGB(0, 255, 0));
                ColorDialog dlg = new ColorDialog(shell);

                dlg.setRGB(colorLabel.getBackground().getRGB());
                dlg.setText("Choose a Color");

                RGB rgb = dlg.open();
                if (rgb != null) {
                    color.dispose();
                    color = new Color(shell.getDisplay(), rgb);
                    colorLabel.setBackground(color);
                    color.dispose();
                }
            }
        });

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

        display.dispose();

    }
}