【问题标题】:Move cursor of JTextField or JComboBox to the start将 JTextField 或 JComboBox 的光标移动到开头
【发布时间】:2012-03-31 08:42:28
【问题描述】:

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

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

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

【问题讨论】:

  • 我的意思是我有可编辑的 JComboBox,内容中有任何文本,当我单击 JComboBox 时,我想将标记移动到可编辑 JComboBox 的开头。默认情况下,它转到文本字段的末尾。当我说字段开始时,我并不是指下拉列表的第一项。
  • 感谢您的澄清。在编辑该评论的整个过程中,我的困惑在某种程度上得到了整理。 :)

标签: java swing jtextfield jcombobox text-cursor


【解决方案1】:
/**
* 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.

【讨论】:

    【解决方案2】:

    你可以使用这个命令

    comp.setCaretPosition(index);

    索引是插入符号的位置。

    【讨论】:

      【解决方案3】:

      我认为这可能是您正在寻找的:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-09
        • 1970-01-01
        • 2011-01-24
        • 1970-01-01
        • 1970-01-01
        • 2011-01-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多