JTextComponent txt = new JFormattedTextField( new PositiveIntegerFormatter() ); txt.addPropertyChangeListener("value", yourPropertyChangeListener); import javax.swing.text.DefaultFormatter; import java.text.ParseException; public class PositiveIntegerFormatter extends DefaultFormatter { static final long serialVersionUID = 1l; public PositiveIntegerFormatter() { setValueClass(Integer.class); setAllowsInvalid(false); setCommitsOnValidEdit(true); } @Override public Object stringToValue(String string) throws ParseException { if (string.equals("")) return null; Integer value = (Integer)super.stringToValue(string); if ( Integer.signum(value.intValue()) < 0 ) throw new ParseException(string, 0); return value; } }
JTextComponent txt = new JFormattedTextField( new LimitedIntegerFormatter(limit) ); txt.addPropertyChangeListener("value", yourPropertyChangeListener); import javax.swing.text.DefaultFormatter; import java.text.ParseException; public class LimitedIntegerFormatter extends DefaultFormatter { static final long serialVersionUID = 1l; private int limit; public LimitedIntegerFormatter( int limit ) { this.limit = limit; setValueClass(Integer.class); setAllowsInvalid(false); setCommitsOnValidEdit(true); } @Override public Object stringToValue(String string) throws ParseException { if (string.equals("")) return null; if (string.length() > limit) throw new ParseException(string, limit); return super.stringToValue(string); } }
formatter.setValueClass(Integer.class); formatter.setMinimum(0); formatter.setMaximum(Integer.MAX_VALUE);
/** * @param networkParameters The network parameters * @param readOnly True if the field is read only */ public FormattedBitcoinAddressField(NetworkParameters networkParameters, boolean readOnly) { super(); Preconditions.checkNotNull(networkParameters, "'networkParameters' must be present"); setInputVerifier(new ThemeAwareBitcoinAddressInputVerifier(networkParameters)); setEditable(!readOnly); setOpaque(false); if (readOnly) { setBorder(new TextBubbleBorder(Themes.currentTheme.readOnlyBorder())); setBackground(Themes.currentTheme.readOnlyBackground()); } else { setBorder(new TextBubbleBorder(Themes.currentTheme.dataEntryBorder())); setBackground(Themes.currentTheme.dataEntryBackground()); } // Build string formatter DefaultFormatter defaultFormatter = new DefaultFormatter(); defaultFormatter.setOverwriteMode(false); defaultFormatter.setValueClass(String.class); setFormatterFactory(new DefaultFormatterFactory(defaultFormatter)); }