我有一个带有一些文本的JTextField
。当我点击文本字段时,光标会移动到字段的末尾。我希望光标在获得焦点时移动到字段的开头。
我在可编辑的JComboBox
中也遇到了同样的问题。
我如何实现在获得焦点时进行光标定位?
我有一个带有一些文本的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(index);
其中,index 是光标位置。
JTextField t = new JTextField();
t.setHorizontalAlignment(JTextField.LEFT);