4

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) {
           }
        });
    }
}
mre
  • 43,520
  • 33
  • 120
  • 170
que1326
  • 2,227
  • 4
  • 41
  • 58

3 Answers3

7

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);

}
aymeric
  • 3,877
  • 2
  • 28
  • 42
4

If first letter it`s not an "a"/"A" or a "t"/"T" or "j"/"J" or a "q"/"Q" or "k"/"K", or any "2","3", ..., "9" I want the textfield to not display anything.

This is job for DocumentFilter with Pattern, simple example

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
2

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

mre
  • 43,520
  • 33
  • 120
  • 170