import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

/**
 * Create a window with 3 similar fields
 * Test the focus to determine which field just lost focus
 * If the number entered is negative, convert to positive.
 *
 */

public class HandleFocus extends JFrame implements FocusListener 
{
    JTextField[] field = new JTextField[3];     //array of 3 textfields

    public static void main(String[] arguments) 
    {
        JFrame frame = new HandleFocus();       //HandleFocus is a subclass of JFrame
    }

    public HandleFocus() 
    {
        super("Focus Gained - Focus Lost");
        setSize(280, 100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        Container panel = getContentPane();     //get reference to the contentPane

        FlowLayout flow = new FlowLayout();     //create a FlowLayout manager   
        panel.setLayout(flow);                  //use it to layout the panel

        JLabel text;
        text = new JLabel("Enter positive or negative numbers");
        panel.add(text);
        text = new JLabel("...on Lost of Focus, change to positive.");
        panel.add(text);

        for (int i = 0; i < 3; i++)                 //loop 3 times
        {
            field[i] = new JTextField("0", 5);      //create a text field

            panel.add(field[i]);                    //add it to the panel

            field[i].addFocusListener(this);        //register an event handler
        }

        setVisible(true);
    }

//-----------------------------------------------------------------------------------
//  Event Handlers for FocusListener
//-----------------------------------------------------------------------------------

    public void focusGained(FocusEvent evt)         //on gaining focus
    {                                               //do nothing - must implement
    }

    public void focusLost(FocusEvent evt)           //on losing focus
    {
        Object source = evt.getSource();            //which field caused the event?

        JTextField field = (JTextField) source;     //cast it to a JTestField

        try 
        {
            float value = Float.parseFloat(field.getText());
            if (value < 0) 
            {
                value = value * -1;             //change to positive
                field.setText("" + value);      //display the value
            }
        } 
        catch (NumberFormatException exc) 
        {
            field.setText("0");
        }
    }
}