JFormattedTextField to format percent numbers?

后端 未结 3 1723
南笙
南笙 2021-01-07 05:04

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

3条回答
  •  走了就别回头了
    2021-01-07 05:59

    1) consider using JSpinner instead of JFormattedTextField because there you can set SpinnerNumberModel for initial values

    from API

    Integer value = new Integer(50); 
    Integer min = new Integer(0);
    Integer max = new Integer(100); 
    Integer step = new Integer(1);
    

    and with simple hack for JSpinner (with SpinnerNumberModel) it doesn't allows another input as Digits, otherwise is there possible input any of Chars

    2) for JFormattedTextField you have to implements

    • DocumentListener
    • Document

    and of both cases for JFormattedTextField you have to write workaround for catch if value is less or more than required range ...

    EDIT:

    .

    enter image description here

    .

    not true at all, :-) you are so far from ... simple wrong :-), there is small mistake with your result, please look at this code

    import java.awt.BorderLayout;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.text.*;
    
    public class TestDigitsOnlySpinner {
    
        public static void main(String... args) {
            SwingUtilities.invokeLater(new Runnable() {
    
                public void run() {
                    JFrame frame = new JFrame("enter digit");
                    JSpinner jspinner = makeDigitsOnlySpinnerUsingDocumentFilter();
                    frame.getContentPane().add(jspinner, BorderLayout.CENTER);
                    frame.getContentPane().add(new JButton("just another widget"), BorderLayout.SOUTH);
                    frame.pack();
                    frame.setVisible(true);
                }
    
                private JSpinner makeDigitsOnlySpinnerUsingDocumentFilter() {
                    JSpinner spinner = new JSpinner(new SpinnerNumberModel());
                    JSpinner.NumberEditor jsEditor = (JSpinner.NumberEditor) spinner.getEditor();
                    JFormattedTextField textField = jsEditor.getTextField();
                    final DocumentFilter digitOnlyFilter = new DocumentFilter() {
    
                        @Override
                        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
                            if (stringContainsOnlyDigits(string)) {
                                super.insertString(fb, offset, string, attr);
                            }
                        }
    
                        @Override
                        public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
                            super.remove(fb, offset, length);
                        }
    
                        @Override
                        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                            if (stringContainsOnlyDigits(text)) {
                                super.replace(fb, offset, length, text, attrs);
                            }
                        }
    
                        private boolean stringContainsOnlyDigits(String text) {
                            for (int i = 0; i < text.length(); i++) {
                                if (!Character.isDigit(text.charAt(i))) {
                                    return false;
                                }
                            }
                            return true;
                        }
                    };
                    /*NumberFormat format = NumberFormat.getIntegerInstance();
                    format.setGroupingUsed(false);// or add the group chars to the filter
                    NumberFormat format = NumberFormat.getInstance();*/
    
                    NumberFormat format = NumberFormat.getPercentInstance();
                    format.setGroupingUsed(false);
                    format.setGroupingUsed(true);// or add the group chars to the filter
                    format.setMaximumIntegerDigits(10);
                    format.setMaximumFractionDigits(2);
                    format.setMinimumFractionDigits(5);
                    textField.setFormatterFactory(new DefaultFormatterFactory(new InternationalFormatter(format) {
    
                        private static final long serialVersionUID = 1L;
    
                        @Override
                        protected DocumentFilter getDocumentFilter() {
                            return digitOnlyFilter;
                        }
                    }));
                    return spinner;
                }
            });
        }
    }
    

提交回复
热议问题