java - Java 中文本字段中的首字母大写

标签 java swing jtextfield documentfilter

是否可以将文本字段中的FIRST字母大写

例如用户输入“hello”,“Hello”就会出现在文本字段中。

我将此代码罚款为将所有字母 http://www.java2s.com/Tutorial/Java/0240__Swing/FormatJTextFieldstexttouppercase.htm 大写

我尝试将其编辑为大写仅第一个字母r认为这是错误的

这是我的编辑

public class UppercaseDocumentFilter extends DocumentFilter {

public void insertString(DocumentFilter.FilterBypass fb, int offset, String text,AttributeSet attr) throws BadLocationException {
    fb.insertString(offset, text.substring(0, 1).toUpperCase() + text.substring(1), attr);
  }

  public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text,AttributeSet attrs) throws BadLocationException {
    fb.replace(offset, length, text.substring(0, 1).toUpperCase() + text.substring(1), attrs);
  }

}

最佳答案

您的方向是正确的,您可以查看 fb.getDocument().getLength() 来确定 Document 的当前长度,当它是0,更新文本的第一个字符

然后您可能可以使用诸如...之类的东西

String text = "testing";
StringBuilder sb = new StringBuilder(text);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
text = sb.toString();
System.out.println(text);

将输入文本的第一个字符大写。您可能想做一些其他检查,但这就是基本想法

示例

似乎对我来说没问题

public class UppercaseDocumentFilter extends DocumentFilter {

    public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
        if (fb.getDocument().getLength() == 0) {
            StringBuilder sb = new StringBuilder(text);
            sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
            text = sb.toString();
        }
        fb.insertString(offset, text, attr);
    }

    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
        if (fb.getDocument().getLength() == 0) {
            StringBuilder sb = new StringBuilder(text);
            sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
            text = sb.toString();
        }
        fb.replace(offset, length, text, attrs);
    }

}

关于java - Java 中文本字段中的首字母大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43195241/

相关文章:

java - 如何将 maven 原型(prototype)从 mvncentral 添加到本地 archetype-repo.xml

Java swing 菜单无法正常显示

java - 如何在 Java 中使用带有托盘图标的上下文菜单?

java - 如何为无法删除的JTextField设置初始值

java - 使用 LiquiBase 和 Spring 将大量值(使用 FK)插入数据库

java - 如何? - 在同一文件执行 GET 之前将字符串插入 php 文件

java - 如何从另一个窗口将项目添加到 JList

java - drawString 方法不起作用

java - 带 Swing 的测试套件

java - 从 JTextfields 中删除焦点