In this small Swing code snippet we demonstrate how to use java.awt.event.KeyAdapter
abstract class to handle keyboard event for the JTextField
component. The snippet will change the characters typed in the JTextField
component to uppercase.
A better approach for this use case is to use the DocumentFilter
class. See the following code snippet How do I format JTextField text to uppercase?.
package org.kodejava.swing;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class UppercaseTextFieldDemo extends JFrame {
public UppercaseTextFieldDemo() throws HeadlessException {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new UppercaseTextFieldDemo().setVisible(true));
}
protected void initComponents() {
// Set default form size, closing event and layout manager
setSize(500, 500);
setTitle("JTextField Key Listener");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
// Create a label and text field for our demo application and add the
// component to the frame content pane object.
JLabel usernameLabel = new JLabel("Username: ");
JTextField usernameTextField = new JTextField();
usernameTextField.setPreferredSize(new Dimension(150, 20));
getContentPane().add(usernameLabel);
getContentPane().add(usernameTextField);
// Register a KeyListener for the text field. Using the KeyAdapter class
// allow us implement the only key listener event that we want to listen,
// in this example we use the keyReleased event.
usernameTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
textField.setText(text.toUpperCase());
}
});
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
No offense, but this is a bad approach and could lead to mutation errors caused by the underlying
Document
been in a state of flux when the key event is triggered. It also does not take into account what will happen if the user pastes text into the field. ADocumentFilter
would be a better and safer choice and is the reason it was implemented, just for this type of use case.Thank you for you correction, I will try to update the example then. Check the following example on
DocumentFilter
, How do I format JTextField text to uppercase?.Nice post. Very informative. This helped me a lot. I am just a Java beginner.