Is there any way to accept only numeric values in a JTextField?
Asked Answered
I

20

51

Is there any way to accept only numeric values in a JTextField? Is there any special method for this?

Indenture answered 21/8, 2009 at 18:1 Comment(2)
Related question: Why is JFormattedTextField evil?Straight
I know this is old, but it might help to actually link to the question. (On second thought, it might just be a broken link due to changes in the system since '09.)Downfall
E
60

As this question re-appears quite often, I put some more effort in this answer then I would usually do.

My vote goes to the JFormattedTextField. IMO each Swing developer should have an improved version of that class in his/her toolkit as it allows to validate almost anything you can think of by the correct choice of Format. Examples for which I already used it:

  • String input where the String may not be empty
  • Coordinate input
  • Date input
  • Editor on a JSpinner
  • Map scales
  • Numbers
  • ...

It also allows for visual feedback when the input is invalid which is for example not the case with the InputVerifier. It still allows to user to input anything, but that value is simply not accepted when not valid and that value never leaves the UI. I think (but again, that is my opinion) that it is better to allow the user to type invalid input that just removing that automatically with e.g. a DocumentFilter. I would suspect a bug when a type a character in a text field and it does not appear.

Let me illustrate this with some code (quite some code actually). First the small demo application. This application just shows a JFormattedTextField for numbers. Just using another format allows to reuse that component for completely different validations.

enter image description here

import be.pcl.swing.ImprovedFormattedTextField;

import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.NumberFormat;

/**
 * See https://mcmap.net/q/345496/-is-there-any-way-to-accept-only-numeric-values-in-a-jtextfield/1076463
 */
public class FormattedTextFieldDemo {
  public static void main( String[] args ) {
    EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        JFrame testFrame = new JFrame( "FormattedTextFieldDemo" );

        NumberFormat integerNumberInstance = NumberFormat.getIntegerInstance();
        ImprovedFormattedTextField integerFormattedTextField = new ImprovedFormattedTextField( integerNumberInstance, 100 );
        integerFormattedTextField.setColumns( 20 );

        testFrame.add( createButtonPanel( integerFormattedTextField ), BorderLayout.NORTH );

        final JTextArea textArea = new JTextArea(50, 50);
        PropertyChangeListener updateTextAreaListener = new PropertyChangeListener() {
          @Override
          public void propertyChange( PropertyChangeEvent evt ) {
            textArea.append( "New value: " + evt.getNewValue() + "\n" );
          }
        };
        integerFormattedTextField.addPropertyChangeListener( "value", updateTextAreaListener );

        testFrame.add( new JScrollPane( textArea ), BorderLayout.CENTER );

        testFrame.setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE );
        testFrame.pack();
        testFrame.setVisible( true );
      }
    } );

  }

  private static JPanel createButtonPanel( final JFormattedTextField aTextField ){
    JPanel panel = new JPanel( new BorderLayout(  ) );
    panel.add( aTextField, BorderLayout.WEST );

    Action action = new AbstractAction() {
      {
        aTextField.addPropertyChangeListener( "editValid", new PropertyChangeListener() {
          @Override
          public void propertyChange( PropertyChangeEvent evt ) {
            setEnabled( ( ( Boolean ) evt.getNewValue() ) );
          }
        } );
        putValue( Action.NAME, "Show current value" );
      }
      @Override
      public void actionPerformed( ActionEvent e ) {
        JOptionPane.showMessageDialog( null, "The current value is [" + aTextField.getValue() + "] of class [" + aTextField.getValue().getClass() + "]" );
      }
    };
    panel.add( new JButton( action ), BorderLayout.EAST );
    return panel;
  }
}

which just shows an ImprovedFormattedTextField and a JButton which is only enabled when the input is valid (aha, eat that DocumentFilter solution). It also shows a JTextArea in which the value is printed each time a new valid value is encountered. Pressing the button shows the value.

The code for the ImprovedFormattedTextField can be found below, together with the ParseAllFormat on which it depends

package be.pcl.swing;

import javax.swing.JFormattedTextField;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.Color;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.text.Format;
import java.text.ParseException;

/**
 * <p>Extension of {@code JFormattedTextField} which solves some of the usability issues</p>
 */
public class ImprovedFormattedTextField extends JFormattedTextField {

  private static final Color ERROR_BACKGROUND_COLOR = new Color( 255, 215, 215 );
  private static final Color ERROR_FOREGROUND_COLOR = null;

  private Color fBackground, fForeground;

  /**
   * Create a new {@code ImprovedFormattedTextField} instance which will use {@code aFormat} for the
   * validation of the user input.
   *
   * @param aFormat The format. May not be {@code null}
   */
  public ImprovedFormattedTextField( Format aFormat ) {
    //use a ParseAllFormat as we do not want to accept user input which is partially valid
    super( new ParseAllFormat( aFormat ) );
    setFocusLostBehavior( JFormattedTextField.COMMIT_OR_REVERT );
    updateBackgroundOnEachUpdate();
    //improve the caret behavior
    //see also http://tips4java.wordpress.com/2010/02/21/formatted-text-field-tips/
    addFocusListener( new MousePositionCorrectorListener() );
  }

  /**
   * Create a new {@code ImprovedFormattedTextField} instance which will use {@code aFormat} for the
   * validation of the user input. The field will be initialized with {@code aValue}.
   *
   * @param aFormat The format. May not be {@code null}
   * @param aValue  The initial value
   */
  public ImprovedFormattedTextField( Format aFormat, Object aValue ) {
    this( aFormat );
    setValue( aValue );
  }

  private void updateBackgroundOnEachUpdate() {
    getDocument().addDocumentListener( new DocumentListener() {
      @Override
      public void insertUpdate( DocumentEvent e ) {
        updateBackground();
      }

      @Override
      public void removeUpdate( DocumentEvent e ) {
        updateBackground();
      }

      @Override
      public void changedUpdate( DocumentEvent e ) {
        updateBackground();
      }
    } );
  }

  /**
   * Update the background color depending on the valid state of the current input. This provides
   * visual feedback to the user
   */
  private void updateBackground() {
    boolean valid = validContent();
    if ( ERROR_BACKGROUND_COLOR != null ) {
      setBackground( valid ? fBackground : ERROR_BACKGROUND_COLOR );
    }
    if ( ERROR_FOREGROUND_COLOR != null ) {
      setForeground( valid ? fForeground : ERROR_FOREGROUND_COLOR );
    }
  }

  @Override
  public void updateUI() {
    super.updateUI();
    fBackground = getBackground();
    fForeground = getForeground();
  }

  private boolean validContent() {
    AbstractFormatter formatter = getFormatter();
    if ( formatter != null ) {
      try {
        formatter.stringToValue( getText() );
        return true;
      } catch ( ParseException e ) {
        return false;
      }
    }
    return true;
  }

  @Override
  public void setValue( Object value ) {
    boolean validValue = true;
    //before setting the value, parse it by using the format
    try {
      AbstractFormatter formatter = getFormatter();
      if ( formatter != null ) {
        formatter.valueToString( value );
      }
    } catch ( ParseException e ) {
      validValue = false;
      updateBackground();
    }
    //only set the value when valid
    if ( validValue ) {
      int old_caret_position = getCaretPosition();
      super.setValue( value );
      setCaretPosition( Math.min( old_caret_position, getText().length() ) );
    }
  }

  @Override
  protected boolean processKeyBinding( KeyStroke ks, KeyEvent e, int condition, boolean pressed ) {
    //do not let the formatted text field consume the enters. This allows to trigger an OK button by
    //pressing enter from within the formatted text field
    if ( validContent() ) {
      return super.processKeyBinding( ks, e,
                                      condition, pressed ) && ks != KeyStroke.getKeyStroke( KeyEvent.VK_ENTER, 0 );
    }
    else {
      return super.processKeyBinding( ks, e,
                                      condition, pressed );
    }
  }

  private static class MousePositionCorrectorListener extends FocusAdapter {
    @Override
    public void focusGained( FocusEvent e ) {
      /* After a formatted text field gains focus, it replaces its text with its
       * current value, formatted appropriately of course. It does this after
       * any focus listeners are notified. We want to make sure that the caret
       * is placed in the correct position rather than the dumb default that is
        * before the 1st character ! */
      final JTextField field = ( JTextField ) e.getSource();
      final int dot = field.getCaret().getDot();
      final int mark = field.getCaret().getMark();
      if ( field.isEnabled() && field.isEditable() ) {
        SwingUtilities.invokeLater( new Runnable() {
          @Override
          public void run() {
            // Only set the caret if the textfield hasn't got a selection on it
            if ( dot == mark ) {
              field.getCaret().setDot( dot );
            }
          }
        } );
      }
    }
  }
}

The ParseAllFormat class:

package be.pcl.swing;

import java.text.AttributedCharacterIterator;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParseException;
import java.text.ParsePosition;

/**
 * <p>Decorator for a {@link Format Format} which only accepts values which can be completely parsed
 * by the delegate format. If the value can only be partially parsed, the decorator will refuse to
 * parse the value.</p>
 */
public class ParseAllFormat extends Format {
  private final Format fDelegate;

  /**
   * Decorate <code>aDelegate</code> to make sure if parser everything or nothing
   *
   * @param aDelegate The delegate format
   */
  public ParseAllFormat( Format aDelegate ) {
    fDelegate = aDelegate;
  }

  @Override
  public StringBuffer format( Object obj, StringBuffer toAppendTo, FieldPosition pos ) {
    return fDelegate.format( obj, toAppendTo, pos );
  }

  @Override
  public AttributedCharacterIterator formatToCharacterIterator( Object obj ) {
    return fDelegate.formatToCharacterIterator( obj );
  }

  @Override
  public Object parseObject( String source, ParsePosition pos ) {
    int initialIndex = pos.getIndex();
    Object result = fDelegate.parseObject( source, pos );
    if ( result != null && pos.getIndex() < source.length() ) {
      int errorIndex = pos.getIndex();
      pos.setIndex( initialIndex );
      pos.setErrorIndex( errorIndex );
      return null;
    }
    return result;
  }

  @Override
  public Object parseObject( String source ) throws ParseException {
    //no need to delegate the call, super will call the parseObject( source, pos ) method
    return super.parseObject( source );
  }
}

Possible improvements:

  • the setBackground is not respected by all Look-and-Feels. Sometimes you can use the setForeground instead, but even that is not guaranteed to be respected by all L&Fs. So for visual feedback it might be better to use an exclamation mark placed next to the field. Drawback is that this might mess up a layout if you suddenly add/remove an icon
  • the feedback only indicates that the input is valid/invalid. There is nothing that indicates what the expected format is. A possible solution is to use a self-created extension of Format which includes a description/example of valid input, and put that as tooltip on the JFormattedTextField.
Electrokinetics answered 16/11, 2012 at 20:44 Comment(3)
@AndrewThompson I needed one. Since this question occurs often I needed an answer I could refer to in the future. And since this question has already got +10k views, it seemed the appropriate place to add such an answerElectrokinetics
Can JFormattedTextField be used to allow only alphabets of variable length?Oldie
@Oldie in the above solution, you can use the formatted text field in combination with any java.util.format implementation you can think ofElectrokinetics
S
13

This question was cited as an 'exact duplicate' of another question that has since been closed. The answers to this question were so poor that I was inspired to help out anybody that might find it later, by linking to a much better answer for this use case.

It is an answer to the closed question & can be summed up as..

Use a JSpinner instead.

Sipple answered 24/5, 2011 at 13:49 Comment(0)
T
10
import javax.swing.*;
import javax.swing.text.*;

public class JNumberTextField extends JTextField
{
    private static final char DOT = '.';
    private static final char NEGATIVE = '-';
    private static final String BLANK = "";
    private static final int DEF_PRECISION = 2;

    public static final int NUMERIC = 2;
    public static final int DECIMAL = 3;

    public static final String FM_NUMERIC = "0123456789";
    public static final String FM_DECIMAL = FM_NUMERIC + DOT;

    private int maxLength = 0;
    private int format = NUMERIC;
    private String negativeChars = BLANK;
    private String allowedChars = null;
    private boolean allowNegative = false;
    private int precision = 0;

    protected PlainDocument numberFieldFilter;

    public JNumberTextField()
    {
        this( 10, NUMERIC );
    }

    public JNumberTextField( int maxLen )
    {
        this( maxLen, NUMERIC );
    }

    public JNumberTextField( int maxLen, int format )
    {
        setAllowNegative( true );
        setMaxLength( maxLen );
        setFormat( format );

        numberFieldFilter = new JNumberFieldFilter();
        super.setDocument( numberFieldFilter );
    }

    public void setMaxLength( int maxLen )
    {
        if (maxLen > 0)
            maxLength = maxLen;
        else
            maxLength = 0;
    }

    public int getMaxLength()
    {
        return maxLength;
    }

    public void setPrecision( int precision )
    {
        if ( format == NUMERIC )
            return;

        if ( precision >= 0 )
            this.precision = precision;
        else
            this.precision = DEF_PRECISION;
    }

    public int getPrecision()
    {
        return precision;
    }

    public Number getNumber()
    {
        Number number = null;

        if ( format == NUMERIC )
            number = new Integer(getText());
        else
            number = new Double(getText());

        return number;
    }

    public void setNumber( Number value )
    {
        setText(String.valueOf(value));
    }

    public int getInt()
    {
        return Integer.parseInt( getText() );
    }

    public void setInt( int value )
    {
        setText( String.valueOf( value ) );
    }

    public float getFloat()
    {
        return ( new Float( getText() ) ).floatValue();
    }

    public void setFloat(float value)
    {
        setText( String.valueOf( value ) );
    }

    public double getDouble()
    {
        return ( new Double( getText() ) ).doubleValue();
    }

    public void setDouble(double value)
    {
        setText( String.valueOf(value) );
    }

    public int getFormat()
    {
        return format;
    }

    public void setFormat(int format)
    {
        switch ( format )
        {
        case NUMERIC:
        default:
            this.format = NUMERIC;
            this.precision = 0;
            this.allowedChars = FM_NUMERIC;
            break;

        case DECIMAL:
            this.format = DECIMAL;
            this.precision = DEF_PRECISION;
            this.allowedChars = FM_DECIMAL;
            break;
        }
    }

    public void setAllowNegative( boolean value )
    {
        allowNegative = value;

        if ( value )
            negativeChars = "" + NEGATIVE;
        else
            negativeChars = BLANK;
    }

    public boolean isAllowNegative()
    {
        return allowNegative;
    }

    public void setDocument( Document document )
    {
    }

    class JNumberFieldFilter extends PlainDocument
    {
        public JNumberFieldFilter()
        {
            super();
        }

        public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException
        {
            String text = getText(0,offset) + str + getText(offset,(getLength() - offset));

            if ( str == null || text == null )
                return;

            for ( int i=0; i<str.length(); i++ )
            {
                if ( ( allowedChars + negativeChars ).indexOf( str.charAt(i) ) == -1)
                    return;
            }

            int precisionLength = 0, dotLength = 0, minusLength = 0;
            int textLength = text.length();

            try
            {
                if ( format == NUMERIC )
                {
                    if ( ! ( ( text.equals( negativeChars ) ) && ( text.length() == 1) ) )
                        new Long(text);
                }
                else if ( format == DECIMAL )
                {
                    if ( ! ( ( text.equals( negativeChars ) ) && ( text.length() == 1) ) )
                        new Double(text);

                    int dotIndex = text.indexOf(DOT);
                    if( dotIndex != -1 )
                    {
                        dotLength = 1;
                        precisionLength = textLength - dotIndex - dotLength;

                        if( precisionLength > precision )
                            return;
                    }
                }
            }
            catch(Exception ex)
            {
                return;
            }

            if ( text.startsWith( "" + NEGATIVE ) )
            {
                if ( !allowNegative )
                    return;
                else
                    minusLength = 1;
            }

            if ( maxLength < ( textLength - dotLength - precisionLength - minusLength ) )
                return;

            super.insertString( offset, str, attr );
        }
    }
}
Taproot answered 7/6, 2012 at 7:55 Comment(1)
new Integer(), new Float(), new Double() and new Long() are deprecated since version 9Andrews
L
7

Although there is the pure evil JFormattedTextField there isn't a trivial way to do it using only the Swing library. The best way to implement this sort of feature is with a DocumentFilter.

(This post originally had links to code and description in my now defunct weblog.)

Lunsford answered 21/8, 2009 at 18:9 Comment(3)
Maybe a more straightforward example of the using Document to filter the input: java2s.com/Code/Java/Swing-JFC/Textfieldonlyacceptsnumbers.htmPassing
I'm curious about @Tom and @banjollity's comments on the evilness of JTextField. So, related question: Why is JFormattedTextField evil?Straight
Link to the question: #1320617Straight
D
4

A simple approach is to subclass JTextField and override createDefaultModel() by returning customised PlainDocument subclass. Example - a textfield for integers only:

public class NumberField extends JTextField {


@Override
protected Document createDefaultModel() {
    return new Numberdocument();
}

class Numberdocument extends PlainDocument
{
    String numbers="1234567890-";
    @Override
    public void insertString(int offs, String str, AttributeSet a)
            throws BadLocationException {
        if(!numbers.contains(str));
        else    super.insertString(offs, str, a);
    }
}

Process input in insertString() any way.

Downwards answered 7/1, 2014 at 18:52 Comment(2)
Thx but perhaps better write if (numbers.contains(str) { super.insertString }Gelasius
@Gelasius Yes, I miss logic sometimes.Downwards
M
3

A quick solution:

JTextField textField = new JTextField() {
  public void processKeyEvent(KeyEvent ev) {
    char c = ev.getKeyChar();
    if (c >= 48 && c <= 57) { // c = '0' ... c = '9'
      super.processKeyEvent(ev);
    }
  }
};

The problem with the above solution is that the user cannot use the Delete, Left Arrow, Right Arrow, or Backspace keys in the text field, so I suggest using this solution:

this.portTextField = new JTextField() {
  public void processKeyEvent(KeyEvent ev) {
    char c = ev.getKeyChar();
    try {
      // Ignore all non-printable characters. Just check the printable ones.
      if (c > 31 && c < 127) {
        Integer.parseInt(c + "");
      }
      super.processKeyEvent(ev);
    }
    catch (NumberFormatException nfe) {
      // Do nothing. Character inputted is not a number, so ignore it.
    }
  }
};
Magpie answered 23/7, 2012 at 9:40 Comment(4)
Please be careful: Not all charcters with an KeyValue >127 are non-printable characters. i.e. '§' or 'ß' can still be entered in the second code-snippet. Just replace 127 with 65535 and check for non-127 (delete key) should work there (i.e. KeyArrows got the value 65535 here). if (c > 31 && c < 65535 && c != 127)Married
-1 because broken solution. This only filters things like typing in a '5'. You can copy/paste in "asdf" without it being filtered.Provenience
@BJ Peter DeLaCruz Thanks for this solution it worked fine for me save a lot of mine time Thanks :)Margaretemargaretha
(1-), Don't play with KeyEvents. Swing has newer and better API's (like a DocumentFilter) that will work in all situations. This solution won't work if you "paste" text into the text field.Herzog
A
3
if (JTextField.getText().equals("") || !(Pattern.matches("^[0-9]+$", JTextField.getText()))) {
     JOptionPane.showMessageDialog(null, " JTextField Invalide !!!!! ");
   }
  • if JTextField.getText().equals("") ==-> if JTextField is empty
  • if(!(Pattern.matches("^[0-9]+$", JTextField.getText()))) ==-> if TextField contains other characters than those
  • JOptionPane.showMessageDialog(null, " JTextField Invalide !!!!! ");==-> so this message will aparate
Arredondo answered 14/5, 2016 at 15:57 Comment(1)
This might be the answer, but add adequate description to support it.Thorson
S
3

Use formatter to format text field.

NumberFormat format = NumberFormat.getInstance();
format.setGroupingUsed(false);
NumberFormatter formatter = new NumberFormatter(format);
formatter.setValueClass(Integer.class);
formatter.setMaximum(65535);
formatter.setAllowsInvalid(false);
formatter.setCommitsOnValidEdit(true);
myTextField = new JFormattedTextField(formatter);
Suprasegmental answered 17/9, 2016 at 1:55 Comment(0)
E
2

Also, consider using an InputVerifier.

Evident answered 24/5, 2011 at 14:15 Comment(0)
S
2

Concidering the number of views this question is getting, i found none of the above solution suitable for my problem. I decided to make a custom PlainDocument to fit my needs. This solution also makes a beep sound when the maximum number of characters used is reached, or the inserted text is not an integer.

private class FixedSizeNumberDocument extends PlainDocument
{
    private JTextComponent owner;
    private int fixedSize;

    public FixedSizeNumberDocument(JTextComponent owner, int fixedSize)
    {
        this.owner = owner;
        this.fixedSize = fixedSize;
    }

    @Override
    public void insertString(int offs, String str, AttributeSet a)
            throws BadLocationException
    {
        if (getLength() + str.length() > fixedSize) {
            str = str.substring(0, fixedSize - getLength());
            this.owner.getToolkit().beep();
        }

        try {
            Integer.parseInt(str);
        } catch (NumberFormatException e) {
            // inserted text is not a number
            this.owner.getToolkit().beep();
            return;
        }

        super.insertString(offs, str, a);
    }               
}

implented as follows:

    JTextField textfield = new JTextField();
    textfield.setDocument(new FixedSizeNumberDocument(textfield,5));
Similar answered 15/11, 2012 at 23:5 Comment(0)
P
1

Try this out in the key pressed event for the related JTextField.

private void JTextField(java.awt.event.KeyEvent evt) {

    // TODO add your handling code here:
    char enter = evt.getKeyChar();
    if(!(Character.isDigit(enter))){
        evt.consume();
    }
}
Photography answered 9/9, 2016 at 17:51 Comment(0)
S
1

A very easy solution is to use a action listener.

TextFieldActionPerformed(java.awt.event.ActionEvent evt) {
    String textFieldValue = TextField.getText();
    try {
        Integer.parseInteger(textFieldValue);
    } catch(Exception e){
        JOptionPane.showMessageDialog(null, "Please insert Valid Number Only");
        TextField.setText(textFieldValue.substring(0,textFieldValue.length()-1));
    }
}

You Can use it for Double as well:

Double.parseDouble(TextField.getText());
Siracusa answered 5/6, 2017 at 18:15 Comment(1)
This only deletes the last character. What if the user inserts a character in the middle?Hollywood
G
1
DataTF.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent eve) {
                String AllowedData="0123456789.";
                char enter = eve.getKeyChar();
                if (!AllowedData.contains(String.valueOf(enter))) {
                    eve.consume();
                }
            }       
        });  
Gennygeno answered 6/5, 2018 at 14:21 Comment(0)
L
0

Look at JFormattedTextField.

Leveroni answered 21/8, 2009 at 18:6 Comment(0)
S
0

write this code into key typed

char c=evt.getKeyChar();
if(!(Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE || c==KeyEvent.VK_DELETE)))
{
    getToolkit().beep();
    evt.consume();
}
Socialminded answered 23/6, 2015 at 10:55 Comment(2)
(1-), Don't play with KeyEvents. Swing has newer and better API's (like a DocumentFilter) that will work in all situations. This solution won't work if you "paste" text into the text field.Herzog
how can I allow '-' and '.' (minus & dot) in this method?Cyrille
H
0

I see many Java programmers are taking Object Oriented Programming too seriously in their code instead of just simplifying things as much. What you can simply do is read the text of JTextField object and check its content with this regular expression using String.match() method at the form submission time. This way it will run or call the events system only once per each form submission:

String regex="^[0-9]+(\.?)[0-9]*$";

This regex will match any decimal number . If the JTextField content is not in the decimal number format, then just write a function return or any logic of exiting or stopping the current context. And if you want it strictly integer then fix the regex as such:

String regex = "^[0-9]+$";

This is a sample code :

class  MyWindow extends JFrame {
 //put this (JTextField input) and the (JButton button) as member variable of 
 //the current class to access it globally easily
 JTextField input=new JTextField(); 
 JButton button =new JButton("Click me");

public MyWindow() {
 button.addActionListener(new ActionListener() {
             @Override
            public void actionPerformed(ActionEvent e) {
               String jtextfield_contents=input.getText().trim();
               String regex="^[0-9]+(\.?)[0-9]*$";
               if (!jtextfield_contents.match(regex) || jtextfield_contents.isBlank()){
                  return; //here is your exit or escape from exceptions point. 
            }
            // below this line and inside actionPerformed
           // write the logic where the input number is considered OK and acceptable to you. 
               }
       );    
 JPanel jp =new JPanel();
 jp.add(button);
 this.add(jp);
 this.setVisible(true);
}
}
Hoopoe answered 14/9, 2022 at 9:59 Comment(0)
R
-1

numberField = new JFormattedTextField(NumberFormat.getInstance());

Formatted text field tutorial

Reina answered 21/8, 2009 at 18:4 Comment(1)
This is also what I thought before I failed and therefore searched here for a solution. Unfortunately JFormattedTextField verifies the input only on leaving the field, not during editing, so an invalid value can be entered. If the input has to be tracked, that's too late.Pharmacopoeia
C
-1

You would like to take a look at JFormattedTextField

Formatted text fields provide a way for developers to specify the valid set of characters that can be typed in a text field

This is a subclass of JTextField, so you can use it like this:

JTextField textField = new JFormattedTextField(NumberFormat.getInstance());
Chivalric answered 21/8, 2009 at 18:4 Comment(0)
J
-1

I think it is the best solution:

JTextField textField = new JFormattedTextField(new MaskFormatter("###")); //
Justin answered 21/10, 2009 at 17:36 Comment(0)
A
-2

You can create a beautiful text field in java that accepts or allows only numeric values.. You can even set the precision for the float values... check the code in zybocodes

Acetic answered 21/4, 2010 at 16:7 Comment(1)
Stating that a question has "a beatiful answer" is not, in and of itself, a good answer. Linking to code is not as good as adding a code snippet, or at least explaining how it is different from other answers.Monospermous

© 2022 - 2024 — McMap. All rights reserved.