Example usage for javax.swing JFormattedTextField setFormatterFactory

List of usage examples for javax.swing JFormattedTextField setFormatterFactory

Introduction

In this page you can find the example usage for javax.swing JFormattedTextField setFormatterFactory.

Prototype

@BeanProperty(visualUpdate = true, description = "AbstractFormatterFactory, responsible for returning an AbstractFormatter that can format the current value.")
public void setFormatterFactory(AbstractFormatterFactory tf) 

Source Link

Document

Sets the AbstractFormatterFactory.

Usage

From source file:Main.java

private static JSpinner makeDigitsOnlySpinnerUsingDocumentFilter() {
    JSpinner spinner = new JSpinner(new SpinnerNumberModel());
    JSpinner.NumberEditor jsEditor = (JSpinner.NumberEditor) spinner.getEditor();
    JFormattedTextField textField = jsEditor.getTextField();
    DocumentFilter digitOnlyFilter = new DocumentFilter() {
        @Override/*from  w  w w .  j a va2  s. c o  m*/
        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.getPercentInstance();
    format.setGroupingUsed(false);
    format.setGroupingUsed(true);
    format.setMaximumIntegerDigits(10);
    format.setMaximumFractionDigits(2);
    format.setMinimumFractionDigits(5);
    textField.setFormatterFactory(new DefaultFormatterFactory(new InternationalFormatter(format) {
        @Override
        protected DocumentFilter getDocumentFilter() {
            return digitOnlyFilter;
        }
    }));
    return spinner;
}