有什么方法可以自动在JTextField事件发生时自动选择JTextAreafocusGained中的文本?

最佳答案

您刚刚说了如何做-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);

07-26 08:21