键入时将文本转换为大写

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了键入时将文本转换为大写相关的知识,希望对你有一定的参考价值。

我有这个带有JTextField的JFrame,我想让我输入的每个字母,在我输入这个JTextField时自动转换为大写。

我正在使用Netbeans。

答案
class UpperCaseDocument extends PlainDocument {
  private boolean upperCase = true;

  public void setUpperCase(boolean flag) {
    upperCase = flag;
  }

  public void insertString(int offset, String str, AttributeSet attSet)
      throws BadLocationException {
    if (upperCase)
      str = str.toUpperCase();
    super.insertString(offset, str, attSet);
  }

}


JTextField tf = new JTextField(20);
UpperCaseDocument ucd = new UpperCaseDocument();
//Associates the editor with a text document. 
tf.setDocument(ucd);

资料来源:Force JTextField to convert input to upper case with PlainDocument in Java

以上是关于键入时将文本转换为大写的主要内容,如果未能解决你的问题,请参考以下文章