当JavaFX中的选定选项卡更改时,如何聚焦特定节点? [英] How to focus a specific node when selected tab changes in JavaFX?
问题描述
我想将焦点设置到选项卡内容中的特定节点.我向 selectedItem 属性中添加了一个 ChangeListener ,如下所示(假设该类包含一个名为 secondNode 且类型为 Node 的字段):
I want to set focus to a specific node in the content of a Tab. I added a ChangeListener to selectedItem property as follows (assume that the class contains a field named secondNode of type Node):
tabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {
@Override
public void changed(ObservableValue<? extends Tab> observable, Tab oldValue, Tab newValue) {
if (newValue != null) {
Platform.runLater(new Runnable() {
@Override
public void run() {
secondNode.requestFocus();
}
});
}
}
});
但是,这不起作用.我认为原因是因为在选择了新标签后,TabPane会执行一些其他操作,这些操作会影响焦点(但是,通过
However, this does not work. I assume the reason is because TabPane performs some additional actions, which affect focus, after the new tab has been selected (but, looking through TabPane source code, I can't figure out what). If I single-step through this code in a debugger, it works as expected, so it appears to be a race condition. If this is so, how can this be resolved?
推荐答案
您可以尝试将Runnable替换为Task:
You could try replacing the Runnable with a Task:
new Thread( new Task<Void>()
{
@Override
public Void call() throws Exception // This is NOT on FX thread
{
Thread.sleep(100);
return null;
}
@Override
public void succeeded() // This is called on FX thread.
{
secondNode.requestFocus();
}
}).start();
这篇关于当JavaFX中的选定选项卡更改时,如何聚焦特定节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!