当focusGained
事件发生时,有什么方法可以默认自动选择JTextField
和JTextArea
中的文本?
最佳答案
您刚刚说了如何去做——FocusListener 的 focusGained 事件。
然后,您可以通过 FocusEvent 的 getSource()
方法获取其获得焦点的 JComponent,然后对其调用 selectAll()
方法。
类似于:
FocusAdapter selectAllFocusAdapter = new FocusAdapter() {
public void focusGained(FocusEvent e) {
final JTextComponent tComponent = (JTextComponent) e.getSource();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
tComponent.selectAll();
}
});
tComponent.selectAll();
}
};
myJTextField.addFocusListener(selectAllFocusAdapter);
otherJTextField.addFocusListener(selectAllFocusAdapter);
myTextArea.addFocusListener(selectAllFocusAdapter);
关于java - swing默认选择文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13553524/