Reset value in text field with FocusListener - Java Swing

Java examples for Swing:Focus Event

Description

Reset value in text field with FocusListener

Demo Code

import java.awt.FlowLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main extends JFrame implements FocusListener {
  JTextField value = new JTextField();

  public Main() {
    super("Enter Numbers");
    setSize(300, 120);/* www .  ja v  a 2  s  .  co m*/
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    FlowLayout flow = new FlowLayout();
    setLayout(flow);

    value = new JTextField("0", 5);
    value.addFocusListener(this);
    add(value);

    setVisible(true);
  }
  public static void main(String[] arguments) {
    JFrame frame = new Main();
  }

  public void focusGained(FocusEvent evt) {
    checkValue(evt.getSource());
  }

  public void focusLost(FocusEvent evt) {
    checkValue(evt.getSource());
  }

  void checkValue(Object source) {
    JTextField field = (JTextField) source;
    try {
      int val = Integer.parseInt(field.getText());
      if (val < 0) {
        val = val * -1;
        field.setText("" + val);
      }
    } catch (NumberFormatException exc) {
      field.setText("0");
    }
  }
}

Related Tutorials