我在我的程序中使用了一些 JFormattedTextFields。由于某种原因,当单击文本字段后文本字段获得焦点时,插入符号位置总是跳到左侧(位置 0)。我希望插入符号最终出现在用户单击的位置。因此,如果我在两位数之间单击,插入符号应该在这两位数之间结束。
所以我实现了一个 FocusListener 来获取点击位置并在那里设置插入符号的位置。
FocusListener focusListener = new FocusListener(){
public void focusGained(FocusEvent evt) {
JFormettedTextField jftf = (JFormattedTextField) evt.getSource();
//This is where the caret needs to be.
int dot = jftf.getCaret().getDot();
SwingUtilities.invokeLater( new Runnable() {
public void run() {
'the textField that has focus'.setCaretPosition('Some how get the evt or dot');
}
});
}
public void focusLost (FocusEvent evt) {}
});
我已经尝试了很多方法来让他工作。我尝试使用 final 关键字,它有效,但仅适用于单个文本字段。
我在焦点侦听器中使用了 set/get 方法来分配当前对象,但不确定如何使这个“安全”(例如,它们是否需要同步?)。
也许我缺少一些东西?