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) {
}
});
}
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With