色をプログラマ側で決定したい場合は、Colorを直接作成すれば済みました。 お絵かきソフト等で、ユーザから色を決めてもらいたい場合には、数値を直接「入力」してもらうという手段もありますが、 もっと直感的に色を「選択」してもらうという方法のほうが、より使い勝手のよいソフトになります。
JFaceツールキットでは、ユーザに色を選択してもらうために、ColorSelectorクラスが用意されています。



ボタンを押すと、色を決定するためのダイアログが表示されます。 任意の色を選んでOKを押すと、canvasエリアがその指定された色になります。
import org.eclipse.jface.preference.ColorSelector;
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.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class ColorSelectorDemonstrate {
public static void main(String[] args) {
final Display display = new Display();
Shell shell = new Shell(display);
final Canvas canvas = new Canvas(shell, SWT.NONE);
canvas.setBounds(0, 30, 100, 100);
// ColorSelectorオブジェクトから、ボタンを作成
final ColorSelector colorSelector = new ColorSelector(shell);
Button button = colorSelector.getButton();
button.setText("色を選択");
button.setLocation(0, 0);
button.pack();
// ボタンに、イベントを追加
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
RGB rgb = colorSelector.getColorValue();
Color canvasBgColor = new Color(display, rgb);
canvas.setBackground(canvasBgColor);
canvas.redraw();
canvas.update();
canvasBgColor.dispose();
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
ColorSelector#getButton()メソッドによって取得されたボタンには、あらかじめリスナーが関連づけられています。 ボタンを押したときにダイアログが表示されるのは、そのリスナにイベントが渡るからです。
サンプルプログラムでは、さらにSelectionListenerを追加しています。 ここで追加したSelectionListenerは、ColorSelectorクラスによるダイアログが呼び出された後に呼び出されます。 そしてColorSelectorオブジェクトからユーザが選択した色を取得し、 それをcanvasの背景カラーに設定して、canvas.redrawを呼び出すことによって、それを反映しています。