Java Swing How to - Change JFormattedTextField focus behaviour








Question

We would like to know how to change JFormattedTextField focus behaviour.

Answer

import java.awt.GridLayout;
import java.text.ParseException;
/* w  ww. j  av  a  2 s . c o  m*/
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.text.MaskFormatter;

public class Main {
  JFormattedTextField jtf1 = createField();
  JFormattedTextField jtf2 = createField();
  JFormattedTextField jtf3 = createField();
  JFormattedTextField jtf4 = createField();
  JButton reset = new JButton("Reset to Default");
  JComboBox combo = new JComboBox();
  JFrame frame = new JFrame("Text Test");

  public Main() {
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocation(150, 150);
    frame.setLayout(new GridLayout(0, 1));
    frame.add(reset);
    frame.add(jtf1);
    frame.add(jtf2);
    frame.add(jtf3);
    frame.add(jtf4);
    frame.add(combo);
    this.initFields();
    reset.addActionListener(e -> {
      initFields();
    });
    for (Edit e : Edit.values()) {
      combo.addItem(e);
    }
    combo.setSelectedIndex(jtf1.getFocusLostBehavior());
    combo.addActionListener(e -> {
      Edit current = (Edit) combo.getSelectedItem();
      jtf1.setFocusLostBehavior(current.getValue());
    });
    frame.pack();
    frame.setVisible(true);
  }

  private void initFields() {
    jtf1.setText("0123456");
    jtf2.setText("01234567");
    jtf3.setText("01234567");
    jtf4.setText("01234567");
  }

  protected JFormattedTextField createField() {
    MaskFormatter formatter = null;
    try {
      formatter = new MaskFormatter("########");
    } catch (ParseException e) {
      e.printStackTrace(System.out);
    }
    JFormattedTextField jtf = new JFormattedTextField(formatter);
    return jtf;
  }

  public static void main(String[] args) {
    Main textTest = new Main();
  }
}

enum Edit {

  COMMIT(JFormattedTextField.COMMIT), COMMIT_OR_REVERT(
      JFormattedTextField.COMMIT_OR_REVERT), REVERT(JFormattedTextField.REVERT), PERSIST(
      JFormattedTextField.PERSIST);
  private int value;

  private Edit(int n) {
    this.value = n;
  }

  public int getValue() {
    return value;
  }

  public static Edit getEnum(int n) {
    for (Edit e : Edit.values()) {
      if (e.value == n) {
        return e;
      }
    }
    return Edit.COMMIT_OR_REVERT;
  }
}