如何监听文本修改组窗口小部件(Java SWT)的事件?

时间:2014-04-22 04:40:16

标签: java events swt listener

我想要做的是:当我更改组小部件的标题时(通过调用setText()方法),我需要检查标题,如果包含某些字符,我会做点什么。< / p>

现在的问题是,如何收听Group widget的文本修改事件?

我尝试了addListener(SWT.Modify, listener);方法,(请参阅下面的示例),它无效。

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

public class Test {

    public static void main(String[] args)
    {
        final Display display = new Display();
        Shell shell = new Shell(display);
        shell.setLayout(new GridLayout(1, false));
        shell.setText("Stackoverflow");

        final Group group = new Group(shell, SWT.NONE);
        group.setText("title0");

        group.addListener(SWT.Modify, new Listener() {

            @Override
            public void handleEvent(Event event) {
                // TODO Auto-generated method stub
                System.out.println("Group title changed");
            }

        });

        Button btn = new Button(shell, SWT.NONE);
        btn.setText("Press to set title of Group."); 

        btn.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                // TODO Auto-generated method stub
                group.setText("title1"); 
            }

        });

        shell.pack();
        shell.open();

        while (!shell.isDisposed())
        {
            if (!display.readAndDispatch())
            {
                display.sleep();
            }
        }
        display.dispose();
    }

}

1 个答案:

答案 0 :(得分:2)

我有解决方法,在setData()类上使用Widget方法,并将PaintListener添加到群组小工具

group.setData(new String(group.getText()));

    group.addPaintListener(new PaintListener() {

        @Override
        public void paintControl(PaintEvent e) {
            if (e.widget instanceof Group) {
                Group grp = (Group)e.widget;
                String data = (String)grp.getData();
                if (!data.equals(grp.getText())) {
                    System.out.println("Title changed");
                    grp.setData(grp.getText()); //Keep new changed title as data
                }
            }

        }
    });

每当标题更改时,paint事件都会触发。我将组窗口小部件标题文本保存为数据并比较绘制侦听器中的更改。

请注意,绘制侦听器将被多次调用,因此建议您在此内部保留非常少的代码。