JavaFX 2:如何以编程方式聚焦表行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20413419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaFX 2: How to focus a table row programmatically?
提问by brnzn
I am trying to select/focus a row of a TableView
programmatically.
我正在尝试以TableView
编程方式选择/聚焦一行。
I can select a row, but it is not getting rendered as focused(not highlighted). I have tried many combinations of the code below, but nothing seems to work.
我可以选择一行,但它没有被渲染为焦点(未突出显示)。我尝试了以下代码的多种组合,但似乎没有任何效果。
table.getSelectionModel().select(0);
table.focusModelProperty().get().focus(new TablePosition(table, 0, column));
table.requestFocus();
Is it possible to highlight a row programmatically?
是否可以以编程方式突出显示一行?
I am using JavaFX 2.2.21
我正在使用 JavaFX 2.2.21
采纳答案by OttPrime
Try putting your request for table focus first and then wrapping the whole thing in a runLater
.
尝试首先将您对表格焦点的请求放在一个runLater
.
Platform.runLater(new Runnable()
{
@Override
public void run()
{
table.requestFocus();
table.getSelectionModel().select(0);
table.getFocusModel().focus(0);
}
});
回答by Jens Piegsa
table.getSelectionModel().select(0);
works for me. Maybe the problem is in your css?
table.getSelectionModel().select(0);
为我工作。也许问题出在你的css中?
回答by Eldelshell
I have two components: a ListView
and a TableView
. When an item in the ListView
is clicked, I want the focus and selection to move to the TableView
and render the selected component in the TableView
. To accomplish this, I did it with:
我有两个组件: aListView
和 a TableView
。ListView
单击 中的项目时,我希望焦点和选择移动到TableView
并在TableView
. 为了做到这一点,我做到了:
void listViewClickHandler(MouseEvent e){
A a = listView.getSelectionModel().getSelectedItem();
if(a != null){
// some stuff
// move focus & selection to TableView
table.getSelectionModel().clearSelection(); // We don't want repeated selections
table.requestFocus(); // Get the focus
table.getSelectionModel().selectFirst(); // select first item in TableView model
table.getFocusModel().focus(0); // set the focus on the first element
tableClickHandler(null); // render the selected item in the TableView
}
void tableClickHandler(MouseEvent e){
B b = table.getSelectionModel().getSelectedItem();
render(b);
}
回答by trilogy
table.getFocusModel().focus(0);
is not needed, but I would also add scrollTo
as well.
table.getFocusModel().focus(0);
不需要,但我也会补充scrollTo
。
Java 8:
爪哇 8:
Platform.runLater(() ->
{
table.requestFocus();
table.getSelectionModel().select(0);
table.scrollTo(0);
});
Java 7:
爪哇7:
Platform.runLater(new Runnable()
{
@Override
public void run()
{
table.requestFocus();
table.getSelectionModel().select(0);
table.scrollTo(0);
}
});