Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a filter for textfields in java swing?

I have a JTextField. And when the user enters a or j, I want the text within the text field to be upper-case (e.g. enter "ab", output "AB"). And if the first letter is not one of the following,

  • a, t,j, q, k, 2, 3, ...,9

I don't want the text field to display anything.

And here's what I have,

public class Gui {
    JTextField tf;
    public Gui(){
        tf = new JTextField();
        tf.addKeyListener(new KeyListener(){
           public void keyTyped(KeyEvent e) {
           }
           /** Handle the key-pressed event from the text field. */
           public void keyPressed(KeyEvent e) {
           }
           /** Handle the key-released event from the text field. */
           public void keyReleased(KeyEvent e) {
           }
        });
    }
}
like image 720
que1326 Avatar asked Dec 12 '22 23:12

que1326


1 Answers

You can override the method insertString of the Document class. Look at an example:

JTextField tf;

public T() {
    tf = new JTextField();
    JFrame f = new JFrame();
    f.add(tf);
    f.pack();
    f.setVisible(true);

    PlainDocument d = new PlainDocument() {
        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            String upStr = str.toUpperCase();
            if (getLength() == 0) {
                char c = upStr.charAt(0);
                if (c == 'A' || c == 'T' || c == 'J' || c == 'Q' || c == 'K' || (c >= '2' && c <= '9')) {
                    super.insertString(offs, upStr, a);
                }
            }

        }
    };
    tf.setDocument(d);

}
like image 164
aymeric Avatar answered Dec 29 '22 01:12

aymeric