Problem using focus listener [message #1017683] |
Tue, 12 March 2013 06:20  |
Eclipse User |
|
|
|
Hi,
I tried to use a FocusListener to check a value from a Text but it does not work, so I tried with a TypedListener (SWT.FocusOut) but it does not work either: when the Text value is empty, the focus should stay in the Text field but it does not...
Here is a snippet:
package test;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class DemoFocus {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new RowLayout());
Composite composite = new Composite(shell, SWT.NONE);
composite.setLayout(new RowLayout());
final Text text = new Text(composite, SWT.NONE);
text.setText("Text 1");
text.addListener(SWT.FocusOut, new Listener () {
public void handleEvent (Event event) {
if (text.getText().equals("")) {
System.out.println("You must provide a value for text 1");
event.doit = false;
text.forceFocus();
}
}
});
/* does not work either
text.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent event) {
if (text.getText().equals("")) {
System.out.println("FOCUSLISTENER You must provide a value for text 1");
text.forceFocus();
}
}
});
*/
Text text2 = new Text(composite, SWT.NONE);
text2.setText("Text 2");
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep ();
}
}
display.dispose();
}
}
Thanks for your help!
|
|
|
Re: Problem using focus listener [message #1017746 is a reply to message #1017683] |
Tue, 12 March 2013 09:25  |
Eclipse User |
|
|
|
I understood why my snippet does not work: setFocus must be called from within an asyncExec:
text.addListener(SWT.FocusOut, new Listener () {
public void handleEvent (Event event) {
if (text.getText().equals("")) {
System.out.println("You must provide a value for text 1");
event.doit = false;
composite.getDisplay().asyncExec(new Runnable() {
public void run() {
text.forceFocus();
}
});
}
}
});
|
|
|
Powered by
FUDForum. Page generated in 0.03320 seconds