SWTではButtonクラスにパラメータを与えることで通常のボタン、トグルボタン、チェックボタン、ラジオボタンなどを使いわけることができます。また、ラベルと同様に画像を貼り付けることも可能です。下の例ではShell#packメソッドでウィンドウの初期サイズを設定しています。packメソッドの働きについてはSwingと同じです。
import org.eclipse.swt.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; public class ButtonSample1 { public static void main (String [] args) { Display display = new Display (); Shell shell = new Shell(display); shell.setText("Button Sample1"); // レイアウトマネージャを設定 shell.setLayout(new FillLayout()); // 普通のボタン Button button1 = new Button(shell,SWT.NULL); button1.setText("Button1"); // トグルボタン Button button2 = new Button(shell,SWT.TOGGLE); button2.setText("Button2"); // チェックボタン Button button3 = new Button(shell,SWT.CHECK); button3.setText("Button3"); shell.pack(); shell.open(); while (!shell.isDisposed ()){ if (!display.readAndDispatch ()){ display.sleep (); } } display.dispose (); } }
org.eclipse.swt.event.SelectionListenerインターフェースを実装したイベントリスナを登録することで、ボタンがクリックされた場合の処理を行うことができます。
Button button = new Button(shell,SWT.NULL); button.setText("Button"); button.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e){ MessageBox mesBox = new MessageBox(shell); mesBox.setMessage("ボタンがクリックされました"); mesBox.open(); } });
Swingと同様に、SWTにも各種リスナインターフェースにアダプタクラスが用意されており、これらを継承すると必要なメソッドをオーバーライドするだけですみます。また、上記の例では無名クラスを使用していますが、リスナを1つのクラスとして実装することも可能です(再利用やコードの見通しを考えるとそのほうがよいでしょう)。
最終更新時間:2004年08月23日 14時20分10秒