金子邦彦研究室プログラミングJava のプログラム例SWT の機能

SWT の機能

このページでは,SWT の機能を,図解で説明する.

ここでは,Eclipse を使う.

準備事項

Shell オブジェクト

プログラムの実例

【要点】

package hoge.hoge.com;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class HelloWorld {
    public static Shell createShell( Display display, String title, int width, int height, boolean resizable, int ncolumns ) {
        // title : ウインドウタイトル
        // widht, height : ウインドウサイズ
        // resizable : サイズ変更を許すか
        // ncolumns : カラム数
        Shell shell = null;
        if ( resizable ) {
            shell = new Shell( display, SWT.TITLE|SWT.MIN|SWT.MAX|SWT.RESIZE);
            // SWT.TITLE : タイトルバーあり
            // SWT.MAX : 最大化ボタンあり
            // SWT.MIN : 最小化ボタンあり
            // SWT.RESIZE : サイズ変更可能
        }
        else {
            shell = new Shell( display, SWT.TITLE );
        }
        shell.setText( title );
        shell.setSize( width, height );
        shell.setLayout( new GridLayout( /* カラム数 */ ncolumns, /* グリッドを均等サイズにするか */ false ) );
        return shell;
    }
    
    public static void main(String[] args) {
        Display display = new Display();
        Shell shell = createShell( display, "HelloWorld!", 200, 100, true, 2 );
        
        Text text1 = new Text( shell, SWT.SINGLE | SWT.BORDER );
        Button button1 = new Button(shell, SWT.BORDER);
        button1.setText("処理開始");
        
        shell.open();
        while (!shell.isDisposed ()) {
            if (!display.readAndDispatch ()) {
                display.sleep ();
            }
        }
        display.dispose ();
    }
}

上記のプログラムの動作画面例

[image]

SWT の Shell オブジェクト

以下,createShell() 関数を使って,SWT の Shell オブジェクトの機能を説明する.

  1. ウインドウタイトルの設定

    以下のように,SWT の Shell オブジェクトには,ウインドウタイトルを設定できる.

    [image]

    ウインドウタイトルには,setText() 関数を使う.

    [image]
  2. ウインドウサイズの設定

    以下のように,SWT の Shell オブジェクトでは,ウインドウサイズを設定できる. ウインドウサイズの設定には,setSize() 関数を使う.

    [image]
  3. リサイズを許すかどうか

    以下のように,SWT の Shell オブジェクトでは,最大化ボタン,最小化ボタン,サイズ変更可能を設定できる.

    [image]

    上のようにするためには,Shell オブジェクトのコンストラクタに,次の3つを含めます.

    [image]

    次のように,最大化ボタン,最小化ボタンを含めたくないし,サイズ変更可能にしたくない場合もあるでしょう.

    [image]

    そのときは,Shell オブジェクトのコンストラクタに, SWT.MAX,SWT.MIN,SWT.RESIZE を含めないということになる.

    [image]
  4. フォーム部品などの配置

    下記のようなフォーム部品の配置については,Shell オブジェクトを使う.

    [image]

    プログラムは,次のようになる.

    [image]