Eclipse大本营


SWT开发 - Button的使用(2) - Radio按钮

2008-01-23 00:42Update

eclipse

本文介绍SWT Button的Radio按钮的创建,事件处理方法。

代码:
ButtonSample02.java
package com.test.swt;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

public class ButtonSample02 {

    public static void main (String [] args) {
        Display display = new Display ();
        final Shell shell = new Shell (display);
        shell.setLayout (new RowLayout (SWT.VERTICAL));
        for (int i=0; i<5; i++) {
            Button button = new Button (shell, SWT.RADIO);
            button.setData("V" + i);
            button.setText ("B" + i);
            
            button.addListener (SWT.Selection, new Listener () {
                public void handleEvent (Event event) {
                    
                    Button widget = (Button)event.widget;
                    if (widget.getSelection()) {
                        MessageBox box1 = new MessageBox(shell,SWT.OK);
                        box1.setMessage(widget.getData().toString());
                        box1.open();
                    }
                }
            });
            
            if (i == 0) button.setSelection (true);
        }
        
        
        shell.pack ();
        shell.open ();
        while (!shell.isDisposed ()) {
            if (!display.readAndDispatch ()) display.sleep ();
        }
        display.dispose ();
    }
}


解说:

使用
Button button = new Button (shell, SWT.RADIO);
来创建radio风格的按钮。

使用
button.setData("V" + i);
语句为radio设置绑定的值,一般按钮的文本可能包含汉字等非英文系文字,所以可以使用为其设置Data来判别到底选中了哪个按钮,这样程序可以根据data值作相应的处理。

button.addListener (SWT.Selection, new Listener () {...
这个语句为其注册事件处理机。

Button widget = (Button)event.widget;
该语句可以取得时间发生的源控件,这里为一个Button控件。

另外,上面使用了MessageBox来提示消息,后面我们将用专门的文章介绍它,这里不再详述。


编译上面的程序,执行后显示:


选中某个选项,弹出一个消息框:
 
Copyright ©2006-2010 lifevv.com. All Rights Reserved
POWERED BY @pmplat.syboos.com