package de.renew.gui.nin;

import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;

/**
 * A text field that is 2 columns wide and can only
 * display non-negative integers.
 * It updates with each input without the need
 * of pressing Enter or loosing focus.
 */
public class FormattedNumberTextField extends JFormattedTextField {

    /**
     * Constructor for the text field with a default value.
     *
     * @param defaultValue set this as default value
     */
    public FormattedNumberTextField(int defaultValue) {

        NumberFormat format = NumberFormat.getInstance();
        NumberFormatter formatter = new NumberFormatter(format);
        formatter.setValueClass(Integer.class);
        formatter.setMinimum(0);
        formatter.setMaximum(Integer.MAX_VALUE);
        formatter.setAllowsInvalid(false);
        formatter.setCommitsOnValidEdit(true);

        setFormatterFactory(new DefaultFormatterFactory(formatter));
        setColumns(2);
        setValue(defaultValue);
    }
}
