我想要做的是:当我更改 Group 小部件的标题时(通过调用 setText()
方法),我需要检查标题,如果包含某些字符,我会这样做东西。
现在的问题是,如何监听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();
}
}
最佳答案
我在这里有解决方法,在 Widget
类上使用 setData()
方法,并将 PaintListener
添加到 Group Widget
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
}
}
}
});
每当标题更改时,绘制事件就会触发。我将组小部件标题文本保留为数据,并比较绘制监听器中的变化。
请注意,绘制监听器将被调用多次,因此建议您在其中保留很少的代码。
关于java - 如何监听组小部件(Java SWT)的文本修改事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23210502/