java - swing默认选择文本

标签 java swing focus jtextfield jtextarea

focusGained 事件发生时,有什么方法可以默认自动选择JTextFieldJTextArea 中的文本?

最佳答案

您刚刚说了如何去做——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/

相关文章:

java - JTable,TableColumnModelListener 检测选定的行

java - 在 Web 服务中使用 htmlunit 时抛出的异常是什么意思?

Java 汇编程序调试

java - 如何让 JComboBox 下拉列表比 JComboBox 本身更宽

java - 如何设置 JButton 的按下背景颜色?

java - 使用 JTextPane 制作文本下划线字体?

.net - WPF中的TabIndex与KeyboardNavigation.TabIndex

通过gtk_menu_popup显示的gtk菜单可以释放焦点吗?

java - 国际资源

java - iReport:如何在没有数据行的情况下隐藏带有文本字段的行包含不同类型的数据