Eclipse大本营


SWT开发 - Button的使用(3) - Toggle风格的按钮

2008-01-23 00:47Update
TAGS: SWT | Button

eclipse

本文介绍怎么创建一组Toggle风格的按钮

代码:

ButtonSample03.java
package com.test.swt;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

public class ButtonSample03 {

    public static void main (String [] args) {
        Display display = new Display ();
        final Shell shell = new Shell (display);
        shell.setLayout (new FillLayout ());
        Listener listener = new Listener () {
            public void handleEvent (Event e) {
                Control [] children = shell.getChildren ();
                for (int i=0; i<children.length; i++) {
                    Control child = children [i];
                    if (e.widget != child && child instanceof Button && (child.getStyle () & SWT.TOGGLE) != 0) {
                        ((Button) child).setSelection (false);
                    }
                }
                ((Button) e.widget).setSelection (true);
            }
        };
        for (int i=0; i<10; i++) {
            Button button = new Button (shell, SWT.TOGGLE);
            button.setText ("B" + i);
            button.addListener (SWT.Selection, listener);
            if (i == 0) button.setSelection (true);
        }
        shell.pack ();
        shell.open ();
        while (!shell.isDisposed ()) {
            if (!display.readAndDispatch ()) display.sleep ();
        }
        display.dispose ();
    }
}


解说:
public void handleEvent (Event e) {...
该代码段用来处理当其中的一个按钮处于选中状态时,将其他的按钮设置为非选中状态。

Button button = new Button (shell, SWT.TOGGLE);
该语句用来创建一个Toggle风格的按钮。

编译执行,显示为:
 
Copyright ©2006-2010 lifevv.com. All Rights Reserved
POWERED BY @pmplat.syboos.com