Don't use a KeyListener.
The Swing Document
supports a DocumentFilter
, which allows you to edit/verify the text before the text is inserted into the Document
.
For example, the following code will convert each character to upper case as it is typed:
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() );
}
}
See the section from the Swing tutorial on Implementing a DocumentFilter for more information and examples.