Java Swing How to - Handle focus event for JFormattedTextField








Question

We would like to know how to handle focus event for JFormattedTextField.

Answer

import java.awt.GridLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.text.NumberFormat;
//from w  ww.jav  a 2s  .c  om
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {
  NumberFormat format = NumberFormat.getNumberInstance();
  JFormattedTextField a = new JFormattedTextField(format);
  JFormattedTextField b = new JFormattedTextField(format);
  JFormattedTextField sum = new JFormattedTextField(format);

  public Main() {
    this.setLayout(new GridLayout(0, 1));
    this.add(init(a));
    this.add(init(b));
    sum.setEditable(false);
    sum.setFocusable(false);
    this.add(sum);
  }
  private JFormattedTextField init(JFormattedTextField jtf) {
    jtf.setValue(0);
    jtf.addFocusListener(new FocusAdapter() {
      @Override
      public void focusLost(FocusEvent e) {
        Number v1 = (Number) a.getValue();
        Number v2 = (Number) b.getValue();
        sum.setValue(v1.longValue() + v2.longValue());
      }
    });
    return jtf;
  }
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new Main());
    f.pack();
    f.setVisible(true);
  }
}