Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-6653596

JFormattedTextField does not select the text on focus gained

      Every text component in the application should select text on focus gained to allow user to replace content in the fastest way. The following singleton class solves the problem:
      ---------- source start ----------
      import java.awt.event.FocusEvent;
      import java.awt.event.FocusListener;
      import javax.swing.text.JTextComponent;

      public final class SelectTextOnFocus
              implements FocusListener {

          private static final SelectTextOnFocus instance = new SelectTextOnFocus();

          public static SelectTextOnFocus instance() {
              return instance;
          }

          private SelectTextOnFocus() {
          }

          public void focusGained(FocusEvent event) {
              Object source = event.getSource();
              if (source instanceof JTextComponent) {
                  JTextComponent text = (JTextComponent) source;
                  text.selectAll();
              }
          }

          public void focusLost(FocusEvent event) {
          }
      }
      ---------- source end ----------

      This solution does not work with JFormattedTextField, because user's listeners is notified before the reformat is started:
      ---------- source start ----------
      public class JFormattedTextField extends JTextField {
          ...
          protected void processFocusEvent(FocusEvent e) {
              super.processFocusEvent(e);
              ...
              if (isEdited() && e.getID() == FocusEvent.FOCUS_LOST) {
                  ...
              }
              else if (!isEdited()) {
                  // reformat
                  setValue(getValue(), true, true); // THIS REFORMAT REMOVES TEXT SELECTION !!!
              }
          }
          ...
      }
      ---------- source end ----------
      So the instance of the SelectTextOnFocus can't be used to provide required functionality. This functionality requires subclassing of the JFormattedTextField that is annoing:
      ---------- source start ----------
      JFormattedTextField text = new JFormattedTextField(formatter) {
          @Override
          protected void processFocusEvent(FocusEvent event) {
              super.processFocusEvent(event);
              if (!e.isTemporary() && (FocusEvent.FOCUS_GAINED == event.getID())) {
                  selectAll();
              }
          }
      };
      ---------- source end ----------

            Unassigned Unassigned
            malenkov Sergey Malenkov (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: