我有一个 JTextField
。当用户输入 a
或 j
时,我希望文本字段中的文本为大写(例如输入“ab”,输出“AB”)。如果第一个字母不是以下之一,
a
,t
,j
,q
,k
,>2
,3
, ...,9
我不希望文本字段显示任何内容。
这就是我所拥有的,
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) {
}
});
}
}
最佳答案
您可以覆盖 Document
类的方法 insertString
。看一个例子:
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);
}
关于java - 如何在 java swing 中为文本字段使用过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11890774/