-1

我需要继续关注 JTextField。应用程序使用 Swing 库。我需要不时关注该领域,以避免将焦点转移到其他组件的用户错误。我想我需要使用 SwingWorker。设置焦点是对 Swing 组件的操作,因此它应该在 EDT 中调用。我的问题是如何编写 SwingWorker 来做到这一点?我知道方法 done() 传递要在 EDT 中调用的任务,但我需要每隔 2 秒调用一次此任务。方法 done() 被调用一次。所以也许这样的事情会好吗?

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;
  }
});
}}

编辑:

我注意到作为 SwingWorker 一部分的方法 process() 可能是合适的,因为它是在 EDT 中调用的。我不确定,但是当我调用 publish() 方法时,可能总是会调用此方法。那么你能告诉我这段代码是否可以有效地完成这项任务吗?

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();
    }
}
4

2 回答 2

1

Surely it's better to limit the user's ability to take focus away from the textfield in the first place? Personally I don't see why it's an issue but I suppose it's better to keep focus in the one component rather than letting the user shift focus only for it to be shifted back every few seconds.

Therefore you could add a FocusListener to the component, override the focusLost method and basically requestFocus() again.

codeBar.addFocusListener(new FocusAdapter() {
    public void focusGained(FocusEvent e) {
    }
    public void focusLost(FocusEvent e) {
        codeBar.requestFocus();
    }
});

NB I've not actually tried this myself but can't see why it wouldn't work.

Alternatively you can use an InputVerifier which always returns false to prevent focus being taken away.

于 2014-07-22T15:30:19.900 回答
1

使用javax.swing.Timer而不是SwingWorker. 在这种情况下actionPerformed将在 EDT 中执行。同样要在组件中设置焦点,您需要调用requestFocus. 顾名思义,这只是一个请求,不能保证。所以你可能会改变你的方法。

Timer timer = new Timer(2000, new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        codeBar.requestFocus();
    }
});

timer.setRepeats(true);
timer.start();
于 2014-07-19T19:48:52.057 回答