默认情况下,有什么方法可以在事件发生时JTextField
自动选择文本?JTextArea
focusGained
问问题
386 次
3 回答
6
你刚刚说了怎么做——一个 FocusListener 的 focusGained 事件。
然后,您可以通过 FocusEvent 的方法获取其焦点已获得的 JComponent,然后在其上getSource()
调用该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);
于 2012-11-25T17:33:04.313 回答
6
这就是你需要的:
jTextField1.selectAll();
更多内容如下:
jTextField1.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
if(jTextField1.getText().equals(initialText))
//jTextField1.setText("");
jTextField1.selectAll();
}
@Override
public void focusLost(FocusEvent e) {
if(jTextField1.getText().equals(""))
jTextField1.setText("whatever");
}
});
于 2012-11-25T17:34:15.040 回答
5
你期待像
class MyFocusTextField extends JTextField {
{
addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
FocusTextField.this.select(0, getText().length());
}
@Override
public void focusLost(FocusEvent e) {
FocusTextField.this.select(0, 0);
}
});
}
}
于 2012-11-25T17:35:45.073 回答