In this tutorial, you will learn how to perform key event in java swing. Here is an example that change the case of characters to uppercase as the user enters any character. The given code accepts the string from the user through the textfield and as the user enters any letter, the letter will get converted automatically into its upper case. We have invoked KeyAdapter to perform the keyReleased function over textfield.
Example:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class TextFieldExample extends JFrame{
JTextField text;
JLabel label;
JPanel p;
TextFieldExample(){
text=new JTextField(15);
label=new JLabel("Enter String:");
p=new JPanel();
p.add(label);
p.add(text);
text.addKeyListener(new KeyAdapter(){
public void keyReleased(KeyEvent e){
String st=text.getText();
text.setText(st.toUpperCase());
}
});
add(p);
setVisible(true);
setSize(300,100);
}
public static void main(String[]args){
TextFieldExample v=new TextFieldExample();
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.