package view;

import java.awt.Color;

import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class NumberDocumentListener implements DocumentListener {
    
    public interface Action{
        public void action( int val );
    }
    
    private Action action;
    private JTextField field;
    
    public NumberDocumentListener( Action callback, JTextField textField )
    {
        action = callback;
        field = textField;
    }
    
    @Override
    public void insertUpdate(DocumentEvent e) {
        try
        {
            action.action( Integer.parseInt( field.getText() ) );
            field.setBackground( Color.WHITE );
        } catch( Exception e1 )
        {
            field.setBackground( Color.RED );
        }
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        try
        {
            action.action( Integer.parseInt( field.getText() ) );
            field.setBackground( Color.WHITE );
        } catch( Exception e1 )
        {
            field.setBackground( Color.RED );
        }
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        try
        {
            action.action( Integer.parseInt( field.getText() ) );
            field.setBackground( Color.WHITE );
        } catch( Exception e1 )
        {
            field.setBackground( Color.RED );
        }
    }
}
