0

こんにちは。常に大文字の値を受け取る必要があるJTextFieldがある画面を開発しています。見てみると、 PlainDocumentから派生したクラスを作成し、insertStringで処理しましたが、機能しました。問題は、JTextFieldの値を編集するたびに、入力している文字列値を挿入する途中ではなく、文字列が上書きされることです。例:自分のフィールドに「JoãodaSilva」という値があり、João 」の直後で「daSilva」の前に「Pedro」という名前追加したい。「 JoãoPedrodaSilva」の代わりに「JoãoPedrolva 」 。ご理解いただければ幸いです。これを修正する方法を知っている人はいますか?私は多くの方法を試しましたが、解決できませんでした。

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

public class UpperCaseField extends JTextField {

    private static final long serialVersionUID = 1L;

    public UpperCaseField() {
        super();
    }

    protected Document createDefaultModel() {
        return new UpperCaseDocument();
    }

    static class UpperCaseDocument extends PlainDocument {

        private static final long serialVersionUID = 1L;

        @Override 
        public void insertString(int offs, String str, AttributeSet a) 
            throws BadLocationException {

            if (str == null) {
                return;
            }
            char[] upper = str.toCharArray();
            for (int i = 0; i < upper.length; i++) {
                upper[i] = Character.toUpperCase(upper[i]);
            }
            super.insertString(offs, new String(upper), a);
        }
    }
}

ありがとう

4

2 に答える 2

1

どうですか:

@Override 
public void insertString(int offs, String str, AttributeSet a) 
            throws BadLocationException {

   if (str == null) {
      return;
   }

   super.insertString(offs, str.toUpperCase(), a);
}
于 2013-01-18T18:30:39.183 に答える
0

メソッドを次のように記述します。

@Override
public void insertString(int offset, String text, AttributeSet attributes) throws BadLocationException {

    if (text != null) {

        int currentBufferLength = getLength();
        String currentBufferContent = getText(0, currentBufferLength);

        String newText;

        if (currentBufferLength == 0) {
            newText = text;
        } else {
            newText = new StringBuilder(currentBufferContent)
                    .insert(offset, text)
                    .toString();
        }

        try {
                super.insertString(offset, text.toUpperCase(), attributes);
        } catch (BadLocationException exception) {
        }

    }
}

申し訳ありませんが、説明する時間がありません。しかし、うまくいけば、比較すると何が間違っているかがわかります。

于 2013-02-15T23:34:05.520 に答える