package util.swing;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class JIntInput extends JTextField {
protected int[] m_anValue;
protected int m_nDefault = 0;
protected int m_nMinimum;
protected int m_nMaximum;
public JIntInput (int[] anValue, int nDefault) {
this (anValue, nDefault, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
public JIntInput (int[] anValue,
int nDefault,
int nMinimum,
int nMaximum) {
super ("0");
m_anValue = anValue;
m_nMinimum = nMinimum;
m_nMaximum = nMaximum;
m_nDefault = ((nDefault >= m_nMinimum)?
((nDefault <= m_nMaximum)?
(nDefault):
(m_nMaximum)):
(m_nMinimum));
m_anValue[0] = m_nDefault;
getDocument().addDocumentListener (new DocumentListener() {
public void changedUpdate (DocumentEvent e) {
performUpdate();
}
public void insertUpdate (DocumentEvent e) {
performUpdate();
}
public void removeUpdate (DocumentEvent e) {
performUpdate();
}
private void performUpdate() {
String sText = getText();
if (sText == "") {
sText = Integer.toString (m_nDefault);
}
try {
m_anValue[0] = Integer.parseInt (sText);
}
catch (NumberFormatException nfe) {}
}
});
setHorizontalAlignment (RIGHT);
setText (Integer.toString (m_nDefault));
}
protected Document createDefaultModel() {
return new PlainDocument() {
private boolean m_fDidSpecialRemove = false;
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (m_fDidSpecialRemove) {
if (getLength() > 0) {
super.remove (0, getLength());
}
offs = 0;
m_fDidSpecialRemove = false;
}
if (str == null) {
return;
}
String sText = getText (0, getLength());
if (sText == null) {
sText = "";
offs = 0;
}
sText = new StringBuffer (sText).insert (offs, str).toString();
try {
int nCounter = Integer.parseInt (sText);
if (nCounter < m_nMinimum) {
return;
}
if (nCounter > m_nMaximum) {
return;
}
super.insertString (offs, str, a);
}
catch (NumberFormatException nfe) {
if (getLength() == 0) {
super.insertString (0, Integer.toString (m_nDefault), a);
}
}
}
public void remove (int offs, int len)
throws BadLocationException {
String sText = getText (0, getLength());
if (sText == null) {
return;
}
sText = new StringBuffer (sText).delete (offs, offs + len).toString();
if (sText.equals ("")) {
sText = null;
}
try {
int nCounter = 0;
if (sText != null) {
nCounter = Integer.parseInt (sText);
}
if ((nCounter < m_nMinimum) ||
(nCounter > m_nMaximum) ||
(sText == null)) {
super.remove (0, getLength());
super.insertString (0, Integer.toString (m_nDefault), null);
m_fDidSpecialRemove = true;
}
else {
super.remove (offs, len);
m_fDidSpecialRemove = false;
}
}
catch (NumberFormatException nfe) {
m_fDidSpecialRemove = false;
}
}
};
}
}