JFormattedTextField for Double still takes charact

2020-02-02 01:08发布

问题:

I have a JFormattedTextField where the user would input prices, I have this, but if I type a character, it'll let me anyway. I need this text field to only read numbers or , from the keyboard, and ignore if it's a char. How should I change it in order to make it work?

JFormattedTextField formattedTextField = new JFormattedTextField();
        formattedTextField.setBounds(25, 330, 56, 20);
        contentPanel.add(formattedTextField);
        formattedTextField.setValue(new Double(10.0));

回答1:

You need to set a Formatter:

NumberFormat f = NumberFormat.getNumberInstance(); 
JFormattedTextField field = new JFormattedTextField(f);

Take a look:
Format
and
NumberFormat

Then try this:

PlainDocument doc = new PlainDocument();
doc.setDocumentFilter(new DocumentFilter() {
    @Override
    public void insertString(FilterBypass fb, int off, String str, AttributeSet attr) 
        throws BadLocationException 
    {
        fb.insertString(off, str.replaceAll("\\D++", ""), attr);  // remove non-digits
    } 
    @Override
    public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr) 
        throws BadLocationException 
    {
        fb.replace(off, len, str.replaceAll("\\D++", ""), attr);  // remove non-digits
    }
});

JFormattedTextField field = new JFormattedTextField();
field.setDocument(doc);


回答2:

A JFormattedTextField can be used for many things, it can be also used to filter dates or phone numbers. You will either need to set a NumberFormater to the TextField or you use the DocumentFilter (works with JTextField only too).

Check this code snippet, that's how you allow only digits in JTextField, by using DocumentFilter, as the most effeciive way :

import java.awt.*;
import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

public class InputInteger
{
    private JTextField tField;
    private MyDocumentFilter documentFilter;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Input Integer Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel();
        contentPane.setBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5));
        tField = new JTextField(10);
        ((AbstractDocument)tField.getDocument()).setDocumentFilter(
                new MyDocumentFilter());        
        contentPane.add(tField); 

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        Runnable runnable = new Runnable()
        {
            @Override
            public void run()
            {
                new InputInteger().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}

class MyDocumentFilter extends DocumentFilter
{   
    @Override
    public void insertString(DocumentFilter.FilterBypass fp
            , int offset, String string, AttributeSet aset)
                                throws BadLocationException
    {
        int len = string.length();
        boolean isValidInteger = true;

        for (int i = 0; i < len; i++)
        {
            if (!Character.isDigit(string.charAt(i)))
            {
                isValidInteger = false;
                break;
            }
        }
        if (isValidInteger)
            super.insertString(fp, offset, string, aset);
        else
            Toolkit.getDefaultToolkit().beep();
    }

    @Override
    public void replace(DocumentFilter.FilterBypass fp, int offset
                    , int length, String string, AttributeSet aset)
                                        throws BadLocationException
    {
        int len = string.length();
        boolean isValidInteger = true;

        for (int i = 0; i < len; i++)
        {
            if (!Character.isDigit(string.charAt(i)))
            {
                isValidInteger = false;
                break;
            }
        }
        if (isValidInteger)
            super.replace(fp, offset, length, string, aset);
        else
            Toolkit.getDefaultToolkit().beep();
    }
}