// NatField: custom Java component: text field that constrains input
// to be numeric.
// Copyright (C) Lemma 1 Ltd. 1997
// Author: Rob Arthan; rda@lemma-one.com

// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.

// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
// The GNU General Public License can be obtained at URL:
// http://www.lemma-one.com/scrapbook/gpl.html
// or by writing to the Free Software Foundation, Inc., 59 Temple Place,
// Suite 330, Boston, MA 02111-1307 USA.

package GUIUtils;

import java.awt.*;

public class NatField extends TextField {

	private int val;

	private int max = -1;

	public NatField(int num, int cols) {
		super(Integer.toString(num < 0 ? 0 : num), cols);
		val = num < 0 ? 0 : num;
	}

	public NatField(int num, int cols, int maximum) {
		super(Integer.toString(num < 0 ? 0 : num), cols);
		val = num < 0 ? 0 : num;
		max = maximum;
	}
	public boolean keyDown (Event evt, int key) {
		return super.keyDown(evt, key);
	}

	public boolean keyUp(Event evt, int key) {
		boolean res = super.keyUp(evt, key);
		boolean revert;
		int new_val;
		try {
			new_val = Integer.parseInt(getText());
			revert = false;
		} catch (NumberFormatException e) {
			int len = getText().length();
			revert = len != 0; // revert if can't convert;
			new_val = 0; // if string is empty new value is 0
		}
		if(new_val < 0) { // revert if negative
			revert = true;
		}
		if(max > 0 && new_val > max) { // revert to max if too big
			val = max;
			revert = true;
		}
		if(revert) {
			setText(Integer.toString(val));
		} else {
			val = new_val;
		}
		return res;
	}

	public int getNat() {
		return val;
	}
}
