Eclipse APIには、org.eclipse.jface.dialogs.Dialog(JFaceのDialogクラス)と、 org.eclipse.swt.widgets.Dialog(SWTのDialogクラス)が存在します。 継承することで、どちらもダイアログを作成する際の基盤として使うことができます。
Dialogクラスの以下のメソッドは、ダイアログを作成するために、上から順に呼び出されます。
Dialog {
protected Control createContents(Composite parent);
protected Control createDialogArea(Composite parent);
protected Control createButtonBar(Composite parent);
protected Control createButtonsForButtonBar(Composite parent);
}
JFaceのDialogクラスを継承して、カスタムダイアログを作成しようとするとき、
これらのメソッドをオーバーライドすることで、自分なりのダイアログを作成することが可能です。
createContentsメソッドは、ダイアログの全体を作成します。
このメソッドは、createDialogAreaメソッドとcreateButtonBarメソッドを呼び出します。
createDialogAreaメソッドは、ボタンの上側の、任意のウィジェット等を表示する領域のcompositeを作成します。
このレイアウトはGridLayoutです。
createButtonBarメソッドは、ダイアログ下側の、ボタンを表示する領域のcompositeの作成とレイアウトの作成を行います。
このメソッドは、createButtonsForButtonBarメソッドを呼び出します。
このレイアウトはGridLayoutです。
createButtonsForButtonBarメソッドは、OKボタンとCancelボタンを作成します。
サンプルとして、複数行のテキスト入力を行うダイアログボックスを作成してみます。
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class MultiTextInputDialog extends Dialog {
// ボタンの上に表示するテキストエリア
private Text text;
// textに入力された文字が反映されるラベル
private Label resultContainer;
// clearボタンのID
private static final int ERASE_ALL_ID = -1;
public MultiTextInputDialog(
Shell parentShell, Label resultContainer) {
super(parentShell);
this.resultContainer = resultContainer;
}
// ダイアログのトップレベル作成
protected Control createContents(Composite parent) {
// createDialogAreaメソッドとcreateButtonBarメソッドの呼び出し
Control control = super.createContents(parent);
// ウィンドウのタイトル設定
control.getShell().setText("複数行の文字列を入力して下さい。");
return control;
}
// ボタンの上のエリアの作成
protected Control createDialogArea(Composite parent) {
text = new Text(parent, SWT.MULTI | SWT.WRAP | SWT.BORDER);
GridData data = new GridData(
GridData.VERTICAL_ALIGN_FILL |
GridData.HORIZONTAL_ALIGN_FILL);
data.widthHint = 300;
data.heightHint = 200;
text.setLayoutData(data);
return parent;
}
// ボタンの作成
protected void createButtonsForButtonBar(Composite parent) {
// clearボタンの作成
createButton(parent, ERASE_ALL_ID, "clear", false);
// OKとCancelボタンの作成
super.createButtonsForButtonBar(parent);
}
// ボタンが押された際のイベントについてオーバーライド
protected void buttonPressed(int buttonId) {
if (ERASE_ALL_ID == buttonId) {
// cancelボタンが押された場合、textのテキストを削除
text.setText("");
} else {
if (IDialogConstants.OK_ID == buttonId) {
// OKボタンが押された際、ラベルにテキストを代入
resultContainer.setText(text.getText());
}
// デフォルトのOKもしくはCancelの動作
super.buttonPressed(buttonId);
}
}
}
open multi-text dialogボタンを押すと、ダイアログが表示されます。
clearボタンを押すと、テキストエリアのそれまで入力された内容が削除されます。
Cnacelボタンを押すと、ダイアログが終了します。
OKボタンを押すと、ダイアログが終了しますが、テキストエリアに入力してあった内容が元のウィンドウに反映されます。

