且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-20 18:56:05

不要使用 KeyListener.

Don't use a KeyListener.

更好的方法是使用 DocumentFilter.

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

This will work whether text is typed or pasted into the text component.

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, 0, 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, offs, 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() );
    }
}

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

The filter can be used on any text component.

请参阅 Swing 教程中关于实施文档过滤器的部分 了解更多信息.

See the section from the Swing tutorial on Implementing a DocumentFilter for more information.