Java Swing How to - Handle lostFocus Event for JTextField








Question

We would like to know how to handle lostFocus Event for JTextField.

Answer

import java.awt.FlowLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
//  w w  w. ja v  a2 s  .co m
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class Main {
  public static void main(String... args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel contentPane = new JPanel();
    contentPane.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
    JTextField tfield1= new JTextField(10);
    JTextField tfield2= new JTextField(10);


    FocusListener tfieldListener = new FocusListener() {
      @Override
      public void focusGained(FocusEvent fe) {
      }
      @Override
      public void focusLost(FocusEvent fe) {
        String num1 = tfield1.getText().trim();
        String num2 = tfield2.getText().trim();
        if (num1 == null || num1.equals(""))
          num1 = "0";
        if (num2 == null || num2.equals(""))
          num2 = "0";
        System.out.println(Integer.toString(Integer.parseInt(num1)
            + Integer.parseInt(num2)));
      }
    };

    tfield1.addFocusListener(tfieldListener);
    tfield2.addFocusListener(tfieldListener);

    ((AbstractDocument) tfield1.getDocument())
        .setDocumentFilter(new MyDocumentFilter());
    ((AbstractDocument) tfield2.getDocument())
        .setDocumentFilter(new MyDocumentFilter());


    contentPane.add(tfield1);
    contentPane.add(tfield2);

    frame.setContentPane(contentPane);
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
  }
}
class MyDocumentFilter extends DocumentFilter {
  @Override
  public void insertString(FilterBypass fb, int offset, String text,
      AttributeSet aset) {
    try {
      super.insertString(fb, offset, text.replaceAll("\\D++", ""), aset);
    } catch (BadLocationException ble) {
      ble.printStackTrace();
    }
  }

  @Override
  public void replace(FilterBypass fb, int offset, int len, String text,
      AttributeSet aset) {
    try {
      super.replace(fb, offset, len, text.replaceAll("\\D++", ""), aset);
    } catch (BadLocationException ble) {
      ble.printStackTrace();
    }
  }
}