I need to keep focus on JTextField. Application uses Swing library. I need set focus on that field from time to time in order to avoid user mistakes that would change focus to other comonents. I suppose I need to use SwingWorker. Set focus is an operation on Swing component so it should be invoked in EDT. My question is how to write SwingWorker to do that? I know that method done() pass tasks to be invoked in EDT but I need this task to be invoked every let's sey 2 seconds. Method done() is called one time. So maybe sth like this will be ok?
public class myWorker extends SwingWorker<Void, Void> {
@Override
protected Void doInBackground() throws Exception {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
//here set focus on JTextField
return null;
}
});
}}
Edit:
I noticed that method process() that is a part of SwingWorker may be appropriate beacuse it is invoked in EDT. I'm not sure but this method is probably invoked always when I call publish() metod. So could you tell me if this code is valid to do this task?
private class KeepFocusWorker extends SwingWorker<Void, Void>
{
@Override
protected Void doInBackground() throws Exception
{
while(true)
{
publish();
}
}
@Override
protected void process(List<Void> chunks)
{
codeBar.requestFocusInWindow();
}
}