JTextField在获得焦点时选择所有内容

时间:2016-03-24 20:28:11

标签: java swing jtextfield focuslistener

我有一个类实现了FocusListener,在类里面得到了很多JTextField,我希望所有这些都在焦点获得时选择所有。这是我的focusGained()函数:

@Override
public void focusGained(FocusEvent fe)
{
    JTextField txt = (JTextField)fe.getComponent();
    txt.selectAll();
}

我尝试将fe转换为组件,然后转换为selectAll(),但它不起作用。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

您需要使用getSource()

((JTextField)fe.getSource()).selectAll();

我会亲自检查instanceof fe.getSource()

@Override
public void focusGained(FocusEvent fe) {
    if (!(fe.getSource() instanceof JTextField)) return;
    JTextField txt = (JTextField)fe.getSource();
    txt.selectAll();
}

答案 1 :(得分:0)

您的代码应该有效,因此我假设侦听器未在JTextField中注册。你必须做某事。像这样(通知addFocusListener方法):

public class MyClass implements FocusListener {
  public JTextField createTextField() {
    JTextField field = new JTextField();

    //add this class as a listener to the textfield
    field.addFocusListener(this);

    return field;
  }

  @Override
  public void focusGained(FocusEvent fe) {
    JTextField txt = (JTextField)fe.getComponent();
    txt.selectAll();
  }

  @Override
  public void focusLost(FocusEvent e) {
  }
}