Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As was pointed out three times so far, this is exactly what <code>DocumentFilter</code>s are made for. Here is a <a href="http://sscce.org/" rel="nofollow">SSCCE</a> that does what you want:</p> <pre><code>import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.JTextField; import javax.swing.text.AbstractDocument; import javax.swing.text.Document; import javax.swing.text.DocumentFilter; import javax.swing.text.BadLocationException; import javax.swing.text.AttributeSet; public class TestDocumentFilter extends JFrame { JTextField basePriceTF; public TestDocumentFilter() { super("TestDocumentFilter"); basePriceTF = new JTextField(); AbstractDocument basePriceDocument = (AbstractDocument) basePriceTF.getDocument(); basePriceDocument.setDocumentFilter(new PositiveIntegerFilter()); getContentPane().add(basePriceTF); } /** * Resets the document to "0" for input values that do not constitut a non-negative integer. */ private static class PositiveIntegerFilter extends DocumentFilter { @Override public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String inputTextValue, AttributeSet attrs) throws BadLocationException { Document oldDoc = fb.getDocument(); String textValue = oldDoc.getText(0, oldDoc.getLength()) + inputTextValue; Integer basePrice = 0; try { basePrice = Integer.parseInt(textValue); } catch (NumberFormatException e) { basePrice = 0; } if (basePrice &lt; 0) basePrice = 0; fb.replace(0, oldDoc.getLength(), basePrice.toString(), attrs); } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new TestDocumentFilter(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }); } } </code></pre> <p>You cannot enter "-1"; the field is reset to "0" when "-" is typed. Note the <code>FilterBypass</code> which avoids any recursive call.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload