SWT3.0 Example Button
概要
Buttonには5つの種類があります。
普通のボタン(SWT.PUSH)・矢印ボタン(SWT.ARROW)・チェックボックス(SWT.CHECK)・ラジオボタン(SWT.RADIO)・トグルボタン(SWT.TOGGLE)です。
Styles

上は左揃え・下は右揃え+FLATスタイル
共通スタイル
SWT.FLATというスタイルがありこれを指定すると見た目が平らな感じになります。ボタンとか押した感じとかは見難くなります。
普通のボタン・チェックボックス・ラジオボタン・トグルボタン のみのスタイル
矢印ボタン以外の4つのボタンはテキストが表示されます。
そのテキストの表示(Align)をスタイルで指定できます。
指定できるスタイルは3つあります。SWT.LEFT(左そろえ)・SWT.CENTER(真ん中そろえ)・SWT.RIGHT(右そろえ)です。
矢印ボタンのみのスタイル
矢印ボタンは矢印の向きをSWT.UP(上矢印)・SWT.DOWN(下矢印)・SWT.LEFT(左矢印)・SWT.RIGHT(右矢印)という風に指定できます。
Event
SelectionListenerでボタンを押しEventを受け取れます。
ただ、他にMouseListenerでも受け取れます。APIによるとSelectionが正しい処理の仕方のようです。
サンプル
単純なボタン
example/button/SimpleButton.java
mainの所はSWTのお約束ではじまります。ボタンは、shellとstyleを指定して作成します。
package example.button;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class SimpleButton {
public SimpleButton(Shell shell) {
shell.setText("simpleButton");
shell.setBounds(0,0,200,100);
shell.setLayout(new FillLayout(SWT.VERTICAL));
Button button;
button=new Button(shell,SWT.NONE);
button.setText("button");
}
public static void main(String[] args) {
Display display=new Display();
Shell shell=new Shell(display);
SimpleButton button=new SimpleButton(shell);
shell.open();
while(!shell.isDisposed()){
if (!display.readAndDispatch ()){
display.sleep ();
}
}
display.dispose();
}
}
イベントを取得するボタン
example/button/SimpleButtonEvent.java
SelectionListenerをimplementsして、buttonにaddSelectionListenerを追加しました。
そしてwidgetSelectedで選択を取得します。
widgetDefaultSelectedは使いませんが、実装しなければならないので、何もしないが付け加えます。
public class SimpleButtonEvent implements SelectionListener {
public SimpleButtonEvent(Shell shell) {
/*
省略
*/
button.addSelectionListener(this);
}
public void widgetSelected(SelectionEvent arg0) {
System.out.println("select");
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
}
選択を取得するボタン
チェックボックス・トグルボタン・ラジオボタンは現在の選択状態を取得できます。
example/button/SimpleButtonSelect.java
選択に状況によりテキストを変更します。
public void widgetSelected(SelectionEvent event) {
Object object=event.getSource();
if(object instanceof Button){
if(((Button)object).getSelection()){
((Button)object).setText("selected");
}else{
((Button)object).setText("not selected");
}
}
}
