将焦点定位在焦点上的JTextField末尾的最佳方法是什么?

Pet*_*eng 2 java swing focus caret jtextfield

默认情况下,当JTextField获得焦点时,插入符号位于文本的开头.但是,我认为更好的行为是将它放在最后,或选择所有文本,例如http://jsfiddle.net/Marcel/jvJzX/.这样做的好方法是什么?理想情况下,该解决方案将全局应用于应用程序中的所有JTextField.

默认行为的示例(按Tab键以聚焦字段):

public static void main(String[] args) {
    JTextField field = new JTextField("hello world!");
    JOptionPane.showMessageDialog(null, field);
}
Run Code Online (Sandbox Code Playgroud)

编辑:为了澄清,如果我不必搜索我的应用程序并更改所有文本字段,那将是很好的.

kle*_*tra 5

无论是实际行为还是要求都没有得到充分描述:

当JTextField获得焦点时,插入符号位于文本的开头

这并不完全正确:当它获得焦点时

  • 单击,插入符号位于鼠标位置
  • 其他方式(标签,程序化)它被放置在焦点丢失时的位置.

因此,要求:

更好的行为是将其定位在最后,或者选择所有文本

需要对这些情况进行一些考虑,以免破坏可用性,至少对于第一个用户可能会被混淆,如果鼠标手势被否决.第二个是有争议的,可能是OS/LAF依赖的.就个人而言,如果它的位置不在起点,我也不会触及插入符号.

从技术上讲,全局触发焦点更改时组件状态更改的解决方案是使用KeyboardFocusManager注册PropertyChangeListener:

PropertyChangeListener pl = new PropertyChangeListener() {

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if (!(evt.getNewValue() instanceof JTextField)) return;
        JTextField field = (JTextField) evt.getNewValue();
        // crude check to not overdo it
        int dot = field.getCaretPosition();
        if (dot == 0) {
            field.selectAll();
        }
    }
};
KeyboardFocusManager.getCurrentKeyboardFocusManager()
    .addPropertyChangeListener("permanentFocusOwner", pl);
Run Code Online (Sandbox Code Playgroud)

  • +1便于全球解决方案.`selectAll()`应该包含在SwingUtilities.invokeLater()中,否则JFormattedTextField上的选择将不起作用. (2认同)