How to use filter for text fields in java swing?

I have a JTextField . And when the user enters a or j , I want the text in the text box to be uppercase (for example, enter "ab", print "AB"). And if the first letter is not one of the following,

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

I do not want the text box to display anything.

And here is 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) { } }); } } 
+4
source share
3 answers

You can override the insertString method of the Document class. See 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); } 
+5
source

If the first letter is not "a" / "A" or "t" / "T" or "j" / "J" or "q" / "Q" or "k" / K ", or any" 2 ", "3", ..., "9" I want the text box to not display anything.

This is a job for DocumentFilter with Pattern , a simple example.

+4
source

Use the JFormattedTextField class. For more information, see How to Use Formatted Text Fields .

+2
source

All Articles