/** @author Scott Marshall @author University of Glasgow, MSc IT Project 2001 @author Building an OnLine Course in Computing Fundamentals */ package ukacgla_BinaryConverter; import javax.swing.*; import javax.swing.text.*; import java.awt.Toolkit; import java.text.ParseException; import java.util.Locale; /** Code based on example Integer checking program Sun Microsystems Site. Validates user entered text as a specific format of String. Other entries are not allowed. Error message displayed if user inputs any value except 0 or 1.*/ public class WholeNumberField extends JTextField { private Toolkit toolkit; public WholeNumberField(String value, int columns) { super(columns); toolkit = Toolkit.getDefaultToolkit(); setValue(value); } /** This is the key method. getValue() is called everytime the table is updated. This method checks it is either a string 0 or 1. If anything else is entered a new InvalidEntryException is thrown. */ protected String getValue() throws InvalidEntryException { String retVal = ""; if (this.getText().equals("0")) retVal = "0"; else if (this.getText().equals("1")) retVal = "1"; else throw new InvalidEntryException("Input must be 0 or 1"); return retVal; } /** This sets the value. All entries have been validated by this stage, and value must be either 0 or 1 */ private void setValue(String value) { if (value.equals("0")) setText(value); else if (value.equals("1")) setText(value); else System.out.println(value); } protected Document createDefaultModel() { return new WholeNumberDocument(); } private class WholeNumberDocument extends PlainDocument { public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { char[] source = str.toCharArray(); char[] result = new char[source.length]; int j = 0; for (int i = 0; i < result.length; i++) { if (Character.isDigit(source[i])) result[j++] = source[i]; else { toolkit.beep(); } } super.insertString(offs, new String(result, 0, j), a); } } }