添加FocusListener
到外地
當focusGained
被觸發,設置字段的文本的末尾插入位置...
field.setCaretPosition(field.getDocument().getLength());
見How to write a focus listener更多細節
更新
要選擇所有文本,y你可以使用...
field.selectAll();
這將移動光標到最後。
我過去所做的是創建一個實用程序類(例如,AutoSelectOnFocusManager
),它有一個單一的FocusListener
。基本上,您註冊(或取消註冊)JTextComponent
s,併爲您管理流程。節省了大量的重複的代碼:P
更新一個簡單的例子
難道這個簡單的例子來測試意見反饋,以爲我只是在重擊,以及...
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Wackme {
public static void main(String[] args) {
new Wackme();
}
public Wackme() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField field1 = new JTextField("Some text", 20);
JTextField field2 = new JTextField("Some text", 20);
field1.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
System.out.println("Move to end");
JTextField field = ((JTextField)e.getComponent());
field.selectAll();
//field.setCaretPosition(field.getDocument().getLength());
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(field1);
frame.add(field2);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
要麼或在結束時光標定位 –
這就是可能是signoficant差,(我的觀點)有兩種方式與卡拉移動到文檔的結尾看@MadProgrammer的答案或selectAll()看我的評論(@MadProgrammer)後 – mKorbel