B.LeeN B.LeeN - 2 months ago 6
Java Question

How to alter Java strings contain only certain alphabetical characters

how can I alter text string fields in java to only contain certain alphabetical characters (f,-)

in this format: 2f5-4, 2f6, 8f9
Only numbers f numbers and
numbers f number - numbers

Answer

You can restrict the characters entered in the field:

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

class JTextFieldFilter extends PlainDocument {
    private final String acceptedChars = "1234567890f-";

    public void insertString(int offset, String  str, AttributeSet attr) throws BadLocationException {
        if(str == null) return;

        for(int i=0; i < str.length(); i++) {
            if(acceptedChars.indexOf(str.valueOf(str.charAt(i))) == -1)
                return;
        }

        super.insertString(offset, str, attr);
    }
}

class FilterDemo extends JFrame {
    private JTextField textField;

    public FilterDemo() {
        super();
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        textField = new JTextField(20);
        textField.setDocument(new JTextFieldFilter());

        Container con = getContentPane();
        con.setLayout(new FlowLayout());

        con.add(textField);
        pack();
    }

    public static void main(String[] args) {
        new FilterDemo().setVisible(true);
    }
}

UPDATE: But you can't validate all the entered text in this way, only single characters at the moment of input. To do this you need something like this:

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.UIManager;
import java.util.regex.*;

class DocListenerDemo extends JFrame {
    private JTextField textField;
    private JButton button;

    public DocListenerDemo() {
        super();
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        textField = new JTextField(20);
        textField.getDocument().addDocumentListener(new DocumentListener() {
            private final Pattern acceptedChars = Pattern.compile("^\\d+(f\\d+(-\\d+)?)?");

            public void changedUpdate(DocumentEvent evt) {
                checkValue(evt);
            }
            public void removeUpdate(DocumentEvent evt) {
                checkValue(evt);
            }
            public void insertUpdate(DocumentEvent evt) {
                checkValue(evt);
            }

            public void checkValue(DocumentEvent evt) {
                Document doc = (Document) evt.getDocument();
                String text = "";

                try {
                    text = doc.getText(0, doc.getLength());
                }
                catch(BadLocationException err) {}

                if(text.isEmpty()) {
                    textField.setBackground(UIManager.getColor("TextField.background"));
                }
                else {
                    if(!acceptedChars.matcher(text).matches()) {
                        button.setEnabled(false);
                        textField.setBackground(Color.PINK);
                    }
                    else {
                        button.setEnabled(true);
                        textField.setBackground(UIManager.getColor("TextField.background"));
                    }                    
                }
            }
        });

        button = new JButton("Click me");
        button.setEnabled(false);

        Container con = getContentPane();
        con.setLayout(new FlowLayout());

        con.add(textField);
        con.add(button);
        pack();
    }

    public static void main(String[] args) {
        new DocListenerDemo().setVisible(true);
    }
}