Java FX 2表单元格编辑和焦点 [英] Java FX 2 Table Cell Editing and Focus
问题描述
我已经学习了一些有关JavaFX 2的知识,但是遇到了可编辑表格单元的问题,我也找不到解决方案.为了节省大量代码,我创建了一个项目,该项目仅包含JavaFX文档中的TableView示例:
I've been learning a bit about JavaFX 2 but I've hit a problem with editable table cells that I can't find a solution too. To save pasting in a lot of code I've created a project that contains only the TableView example from the JavaFX documentation: http://docs.oracle.com/javafx/2/ui_controls/table-view.htm
如果运行此代码,则会看到以下行为:
If you run up this code you see this behaviour:
- 单击一行将选择该行.
- 单击所选行中的单元格会将单元格转换为文本字段,以便可以对其进行编辑.
- 单击文本字段可以编辑内容.
问题在于单击三下即可到达可编辑单元格的位置.我想实现的是当创建的文本字段(例如第2步)焦点直接切换到文本字段时.
The problem is that's three clicks to get to the point where the cell can be edited. What I would like to achieve is when the text field in created (e.g. step 2) focus switches to the text field directly.
关于如何实现此目标的最佳猜测是在startEditing()
方法的末尾添加textField.requestFocus()
:
My best guess regarding how to achieve this was to add textField.requestFocus()
to the end of the the startEditing()
method:
@Override
public void startEdit() {
super.startEdit();
if (textField == null) {
createTextField();
}
setGraphic(textField);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
textField.selectAll();
textField.requestFocus();
}
但这不起作用.如果我在文本字段中添加焦点侦听器,我会发现它获得了焦点,但随后又失去了焦点.在侦听器中插入一个断点似乎表明TableView在显示文本字段之前已重新获得焦点.
but this doesn't work. If I add a focus listener to the text field what I find is that it gets focus but then looses it again. Sticking a break point in the listener seems to indicate that the TableView is taking focus back before the text field is displayed.
因此,问题是开始编辑时如何将焦点放在文本字段上?
The question therefore is how do I give focus to the text field when editing starts?
推荐答案
能否将textField.requestFocus();
行替换为:
Platform.runLater(new Runnable() {
@Override
public void run() {
textField.requestFocus();
}
});
然后重试.
这篇关于Java FX 2表单元格编辑和焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!