如何在java swing中使用文本字段的过滤器?

que*_*326 4 java swing keylistener jtextfield

我有一个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) {
           }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

aym*_*ric 5

您可以覆盖的方法insertString中的Document类.看一个例子:

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

}
Run Code Online (Sandbox Code Playgroud)