繁体   English   中英

将JTextField或JComboBox的光标移动到开头

[英]Move cursor of JTextField or JComboBox to the start

我有一个带有一些文本的JTextField 当我单击文本字段时,光标移动到字段的末尾。 我希望光标在聚焦时移动到字段的开头。

我对可编辑的JComboBox有同样的问题。

如何在焦点上实现此光标定位?

/**
* On gaining focus place the cursor at the start of the text.
*/
public class CursorAtStartFocusListener extends FocusAdapter {

    @Override
    public void focusGained(java.awt.event.FocusEvent evt) {
        Object source = evt.getSource();
        if (source instanceof JTextComponent) {
            JTextComponent comp = (JTextComponent) source;
            comp.setCaretPosition(0);
        } else {
            Logger.getLogger(getClass().getName()).log(Level.INFO,
                    "A text component expected instead of {0}",
                    source.getClass().getName());
        }
    }
}

jTextField1.addFocusListener(new CursorAtStartFocusListener());
jComboBox1.getEditor().getEditorComponent().addFocusListener(new CursorAtStartFocusListener());
// Only one instance of CursorAtStartFocusListener needed.

您可以使用此命令

comp.setCaretPosition(索引);

指数是插入位置。

我想这可能就是你要找的东西:

JTextField t = new JTextField();
t.setHorizontalAlignment(JTextField.LEFT);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM