Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9162693
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T14:16:18+00:00 2026-06-17T14:16:18+00:00

I have a JFormattedTextField using the following mask formatter: private MaskFormatter maskForInput; maskForInput=new MaskFormatter(####);

  • 0

I have a JFormattedTextField using the following mask formatter:

    private MaskFormatter maskForInput;
    maskForInput=new MaskFormatter("####"); // I have tried using stars (*) too.
    maskForInput.setValidCharacters("0123456789");

    javax.swing.JFormattedTextField playerRaiseField=new javax.swing.JFormattedTextField(maskForInput);

This is supposed to allow the user to enter up to 4 digits as an input. However when I am trying to Integer.parseInt(playerRaiseField.getText()) the String returned from this field I am always getting a NumberFormatException possibly due to the empty spaces left on user input.
To clear this up:

If the user inputs 560 for example there is a trailing space left behind so the String I am reading is 560( ) and when trying to parse this String into an int this exception is thrown. Any workarounds? How can I modify the mask formatter to accept 1 to 4 digits and not always 4 digits fixed??

Note: Curiously enough using trim() on the String returned is still not removing the extra whitespace character…

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T14:16:20+00:00Added an answer on June 17, 2026 at 2:16 pm

    There are a number of things wrong with your expectations…

    Firstly, you seem to believe that a formatted field can have any number of characters. This isn’t true (while you can get the text, the field remains in what it considers to be an invalid state). The formatted field expects that the all the places of the mask must be filled.

    Secondly, you should be using the JFormattedTextField#getValue method to return the value of the field, not getText

    Thirdly, the text being returned is filled with the mask’s placeholder character (MaskFormatter#getPlaceholder), which may or may not be a space, so String#trim probably isn’t going to be of help…

    If you want the user to only be able to enter a numeric value, which may consist of 0-n characters, then you really should consider using a DocumentFilter applied to normal JTextField

    public class TestField {
    
        public static void main(String[] args) {
            new TestField();
        }
    
        public TestField() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (Exception ex) {
                    }
    
                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class NumericDocumentFilter extends DocumentFilter {
    
            private int maxChars;
    
            public NumericDocumentFilter(int maxChars) {
                this.maxChars = maxChars;
            }
    
            @Override
            public void insertString(DocumentFilter.FilterBypass fb, int offset,
                    String text, AttributeSet attr)
                    throws BadLocationException {
    
                StringBuilder buffer = new StringBuilder(text);
                for (int i = buffer.length() - 1; i >= 0; i--) {
                    char ch = buffer.charAt(i);
                    if (!Character.isDigit(ch)) {
                        buffer.deleteCharAt(i);
                    }
                }
    
                text = buffer.toString();
                if (fb.getDocument().getLength() + text.length() > maxChars) {
                    int remaining = maxChars - fb.getDocument().getLength();
                    text = text.substring(0, remaining);
                }
    
                if (text.length() > 0) {
                    super.insertString(fb, offset, text, attr);
                }
            }
    
            @Override
            public void replace(DocumentFilter.FilterBypass fb,
                    int offset, int length, String string, AttributeSet attr) throws BadLocationException {
                if (length > 0) {
                    fb.remove(offset, length);
                }
                insertString(fb, offset, string, attr);
            }
        }
    
        public class TestPane extends JPanel {
    
            private JTextField field;
    
            public TestPane() {
    
                setLayout(new GridBagLayout());
    
                field = new JTextField(4);
                ((AbstractDocument) field.getDocument()).setDocumentFilter(new NumericDocumentFilter(4));
                add(field);
                field.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.out.println(field.getText());
                    }
                });
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code: public test() { setLayout(new FlowLayout()); JFormattedTextField price = new
I have applied a Formatter to a JFormattedTextField using a FormatterFactory , when a
I have a field as: jFormattedTextFieldGrossWeight = new javax.swing.JFormattedTextField(); jFormattedTextFieldGrossWeight.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat(#,##0.00)))); I
Have the following code: String s= v.request(engine/?key=, P4z72NmBa91&method=load); JSONParser parser = new JSONParser(); Object
I have created a custom component (NumberFormattedTextField) of JFormattedTextField. This is the Formatter I
Have got a method which returns IEnumerable<User> which I have been using Linq /
Have have this line of code in my form when I create a new
I have been trying to create a JFormattedTextField array which populates in a pane.
I have the following code : NumberFormat nf=NumberFormat.getInstance(Locale.FRANCE); nf.setMinimumFractionDigits(3); String s= nf.format(3456.32); // double
Have the following cronjob set up in root's crontab: (centos 5.x) 2 * *

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.