javaswinguser-interfacejeditorpane

How to automatically update small letter characters to capital letter in Java JEditorPane?


So I want to automatically convert all entered characters to uppercase.

Here is relevant part of the code :

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

And the UIKeyListener Class I am only providing the keyReleased function as other part is just boilerplate code

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

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

This is mostly OK but the problems are :-

Now The first problem is solved if I call the capitalize function from keyTyped function but there there is a new problem : the last typed letter remains small

And I also want to ask whether can we do this without listening to keyevents like by default the editorpane will only accept capital letters?


Solution

  • Don't use a KeyListener.

    A better approach is to use a 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.

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