我在我的程序中使用了一些 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 方法来分配当前对象,但不确定如何使其“安全”(例如,它们是否需要同步?)。
也许我遗漏了什么?
最佳答案
您需要使用 MouseListener:
MouseListener ml = new MouseAdapter()
{
public void mousePressed(final MouseEvent e)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JTextField tf = (JTextField)e.getSource();
int offset = tf.viewToModel(e.getPoint());
tf.setCaretPosition(offset);
}
});
}
};
formattedTextField.addMouseListener(ml);
关于java - JFormattedTextField 插入符号在焦点上的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2201873/