如何在 Java JEditorPane 中自动将小写字母更新为大写字母?

问题描述

所以我想将所有输入的字符自动转换为大写。

这是代码的相关部分:

editorPane = new JEditorPane();
editorPane.getCaret().setBlinkRate(0);
this.keyListener = new UIKeyListener(editorPane);
editorPane.addKeyListener(keyListener);

而 UIKeyListener 类我只提供 keyreleased 函数,因为其他部分只是样板代码

@Override
public void keyreleased(KeyEvent e) {
    capitalizeCode();
}

private void capitalize() {
    int prevCarerPosition = editorPane.getcaretposition();
    editorPane.setText(editorPane.getText().toupperCase());
    editorPane.setCaretPosition(prevCarerPosition);
}

这基本上没问题,但问题是:-

  • 我无法选择文本
  • 每次我输入字符时,它们首先以小写字母出现,然后变成大写字母

现在,如果我从 keyTyped 函数调用大写函数,第一个问题就解决了,但有一个新问题:最后输入的字母仍然很小

而且我还想问一下,我们是否可以在不听键事件的情况下执行此操作,例如认情况下编辑器窗格只接受大写字母?

解决方法

不要使用 KeyListener。

更好的方法是使用 DocumentFilter

无论文本是键入还是粘贴到文本组件中,这都将起作用。

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class UpperCaseFilter extends DocumentFilter
{
    public void insertString(FilterBypass fb,int offs,String str,AttributeSet a)
        throws BadLocationException
    {
        replace(fb,offs,str,a);
    }

    public void replace(FilterBypass fb,final int offs,final int length,final String text,final AttributeSet a)
        throws BadLocationException
    {
        if (text != null)
        {
            super.replace(fb,length,text.toUpperCase(),a);
        }
    }

    private static void createAndShowGUI()
    {
        JTextField textField = new JTextField(10);
        AbstractDocument doc = (AbstractDocument) textField.getDocument();
        doc.setDocumentFilter( new UpperCaseFilter() );

        JFrame frame = new JFrame("Upper Case Filter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout( new java.awt.GridBagLayout() );
        frame.add( textField );
        frame.setSize(220,200);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
    }
}

过滤器可用于任何文本组件。

有关详细信息,请参阅 Implementing a DocumentFilter 上的 Swing 教程部分。