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

  • Home
  • SEARCH
  • 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 6618529
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T20:50:45+00:00 2026-05-25T20:50:45+00:00

I would like to format a float number as a percent-value with JFormattedTextField that

  • 0

I would like to format a float number as a percent-value with JFormattedTextField that allows inputs from 0 to 100 percent (converted to 0.0f-1.0f), always shows the percent sign and disallows any invalid characters.

Now I have experimented a bit with NumberFormat.getPercentInstance() and the NumberFormatter attributes but without success.

Is there a way to create a JFormattedTextField that obeys to these rules with the standard classes? Or do I have to implement my own NumberFormatter?

That’s what I have so far (no way to input 100%, entering a 0 breaks it completly):

public class MaskFormatterTest {
    public static void main(String[] args) throws Exception {
        JFrame frame = new JFrame("Test");
        frame.setLayout(new BorderLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        NumberFormat format = NumberFormat.getPercentInstance();
        NumberFormatter formatter = new NumberFormatter(format);
        formatter.setMaximum(1.0f);
        formatter.setMinimum(0.0f);
        formatter.setAllowsInvalid(false);
        formatter.setOverwriteMode(true);
        JFormattedTextField tf = new JFormattedTextField(formatter);
        tf.setColumns(20);
        tf.setValue(0.56f);

        frame.add(tf);
        frame.pack();
        frame.setVisible(true);
    }
}
  • 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-05-25T20:50:45+00:00Added an answer on May 25, 2026 at 8:50 pm

    Ok, I’ve made it. The solution is far from simple, but at least it does exactly what I want. Except for returning doubles instead of floats. One major limitation is that it does not allow fraction digits, but for now I can live with that.

    import java.awt.BorderLayout;
    import java.text.NumberFormat;
    import java.text.ParseException;
    
    import javax.swing.JComponent;
    import javax.swing.JFormattedTextField;
    import javax.swing.JSpinner;
    import javax.swing.SpinnerNumberModel;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DefaultFormatterFactory;
    import javax.swing.text.DocumentFilter;
    import javax.swing.text.NavigationFilter;
    import javax.swing.text.NumberFormatter;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.Position.Bias;
    
    public class JPercentField extends JComponent {
    
        private static final double MIN_VALUE = 0.0d;
        private static final double MAX_VALUE = 1.0d;
        private static final double STEP_SIZE = 0.01d;
    
        private static final long serialVersionUID = -779235114254706347L;
    
        private JSpinner spinner;
    
        public JPercentField() {
            initComponents();
            initLayout();
            spinner.setValue(MIN_VALUE);
        }
    
        private void initComponents() {
            SpinnerNumberModel model = new SpinnerNumberModel(MIN_VALUE, MIN_VALUE, MAX_VALUE, STEP_SIZE);
            spinner = new JSpinner(model);
            initSpinnerTextField();
        }
    
        private void initSpinnerTextField() {
            DocumentFilter digitOnlyFilter = new PercentDocumentFilter(getMaximumDigits());
            NavigationFilter navigationFilter = new BlockLastCharacterNavigationFilter(getTextField());
            getTextField().setFormatterFactory(
                    new DefaultFormatterFactory(new PercentNumberFormatter(createPercentFormat(), navigationFilter,
                            digitOnlyFilter)));
            getTextField().setColumns(6);
        }
    
        private int getMaximumDigits() {
            return Integer.toString((int) MAX_VALUE * 100).length();
        }
    
        private JFormattedTextField getTextField() {
            JSpinner.NumberEditor jsEditor = (JSpinner.NumberEditor) spinner.getEditor();
            JFormattedTextField textField = jsEditor.getTextField();
            return textField;
        }
    
        private NumberFormat createPercentFormat() {
            NumberFormat format = NumberFormat.getPercentInstance();
            format.setGroupingUsed(false);
            format.setMaximumIntegerDigits(getMaximumDigits());
            format.setMaximumFractionDigits(0);
            return format;
        }
    
        private void initLayout() {
            setLayout(new BorderLayout());
            add(spinner, BorderLayout.CENTER);
        }
    
        public double getPercent() {
            return (Double) spinner.getValue();
        }
    
        public void setPercent(double percent) {
            spinner.setValue(percent);
        }
    
        private static class PercentNumberFormatter extends NumberFormatter {
    
            private static final long serialVersionUID = -1172071312046039349L;
    
            private final NavigationFilter navigationFilter;
            private final DocumentFilter digitOnlyFilter;
    
            private PercentNumberFormatter(NumberFormat format, NavigationFilter navigationFilter,
                    DocumentFilter digitOnlyFilter) {
                super(format);
                this.navigationFilter = navigationFilter;
                this.digitOnlyFilter = digitOnlyFilter;
            }
    
            @Override
            protected NavigationFilter getNavigationFilter() {
                return navigationFilter;
            }
    
            @Override
            protected DocumentFilter getDocumentFilter() {
                return digitOnlyFilter;
            }
    
            @Override
            public Class<?> getValueClass() {
                return Double.class;
            }
    
            @Override
            public Object stringToValue(String text) throws ParseException {
                Double value = (Double) super.stringToValue(text);
                return Math.max(MIN_VALUE, Math.min(MAX_VALUE, value));
            }
        }
    
        /**
         * NavigationFilter that avoids navigating beyond the percent sign.
         */
        private static class BlockLastCharacterNavigationFilter extends NavigationFilter {
    
            private JFormattedTextField textField;
    
            private BlockLastCharacterNavigationFilter(JFormattedTextField textField) {
                this.textField = textField;
            }
    
            @Override
            public void setDot(FilterBypass fb, int dot, Bias bias) {
                super.setDot(fb, correctDot(fb, dot), bias);
            }
    
            @Override
            public void moveDot(FilterBypass fb, int dot, Bias bias) {
                super.moveDot(fb, correctDot(fb, dot), bias);
            }
    
            private int correctDot(FilterBypass fb, int dot) {
                // Avoid selecting the percent sign
                int lastDot = Math.max(0, textField.getText().length() - 1);
                return dot > lastDot ? lastDot : dot;
            }
        }
    
        private static class PercentDocumentFilter extends DocumentFilter {
    
            private int maxiumDigits;
    
            public PercentDocumentFilter(int maxiumDigits) {
                super();
                this.maxiumDigits = maxiumDigits;
            }
    
            @Override
            public void insertString(FilterBypass fb, int offset, String text, AttributeSet attrs)
                    throws BadLocationException {
                // Mapping an insert as a replace without removing
                replace(fb, offset, 0, text, attrs);
            }
    
            @Override
            public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
                // Mapping a remove as a replace without inserting
                replace(fb, offset, length, "", SimpleAttributeSet.EMPTY);
            }
    
            @Override
            public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
                    throws BadLocationException {
                int replaceLength = correctReplaceLength(fb, offset, length);
                String cleanInput = truncateInputString(fb, filterDigits(text), replaceLength);
                super.replace(fb, offset, replaceLength, cleanInput, attrs);
            }
    
            /**
             * Removes all non-digit characters
             */
            private String filterDigits(String text) throws BadLocationException {
                StringBuilder sb = new StringBuilder(text);
                for (int i = 0, n = sb.length(); i < n; i++) {
                    if (!Character.isDigit(text.charAt(i))) {
                        sb.deleteCharAt(i);
                    }
                }
                return sb.toString();
            }
    
            /**
             * Removes all characters with which the resulting text would exceed the maximum number of digits
             */
            private String truncateInputString(FilterBypass fb, String filterDigits, int replaceLength) {
                StringBuilder sb = new StringBuilder(filterDigits);
                int currentTextLength = fb.getDocument().getLength() - replaceLength - 1;
                for (int i = 0; i < sb.length() && currentTextLength + sb.length() > maxiumDigits; i++) {
                    sb.deleteCharAt(i);
                }
                return sb.toString();
            }
    
            private int correctReplaceLength(FilterBypass fb, int offset, int length) {
                if (offset + length >= fb.getDocument().getLength()) {
                    // Don't delete the percent sign
                    return offset + length - fb.getDocument().getLength();
                }
                return length;
            }
        }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i would like to know how to format float number. Float Want to display
I have a date and I would like to format the date like that:
I have a function that returns a float from 0 to 255. I would
I would like to display the a number value to the max number of
I would like to set some initial variables (like format compact and the current
I would like to format a price in JavaScript. I'd like a function which
I have a workbook with two sheets. I would like to format the cell
I would like to color format the text printed to the console using the
I would like to create a file format for my app like Quake, OO,
I would like to document the file format of regedit utility, so data can

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.