4

私は持っていJTextFieldます。また、ユーザーがaorjを入力すると、テキスト フィールド内のテキストを大文字にする必要があります (たとえば、「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) {
           }
        });
    }
}
4

3 に答える 3

7

クラスのメソッド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);

}
于 2012-08-09T20:05:20.900 に答える
4

最初の文字が「a」/「A」でも「t」/「T」でも「j」/「J」でも「q」/「Q」でも「k」/「K」でもない場合、または任意の「2」、「3」、...、「9」 テキストフィールドに何も表示しないようにします。

これはPatternを使用したDocumentFilterのジョブです 。簡単な

于 2012-08-09T19:51:13.633 に答える
2

JFormattedTextFieldクラスを使用します。詳細については、書式設定されたテキスト フィールドの使用方法 を参照してください。

于 2012-08-09T19:48:27.593 に答える