Handling Key Board Events
Java program that demonstrates the use of KeyAdapter and handles key events. In this example, we’ll create a basic frame and override the keyPressed() method from KeyAdapter to respond to key presses.
import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample {
public static void main(String[] args) {
Frame frame = new Frame("KeyAdapter Example");
frame.setSize(400, 400);
frame.setLayout(null);
Label label = new Label("Press a key...");
label.setBounds(150, 180, 100, 20);
frame.add(label);
// Add a KeyListener using KeyAdapter
frame.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// Handle key press events
int keyCode = e.getKeyCode();
label.setText("Key code: " + keyCode);
}
});
// Add a WindowListener to close the program
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0); // Exit the program
}
});
frame.setVisible(true);
}
}
In this program:
We create a Frame named “KeyAdapter Example.”
We add a KeyAdapter to the frame using frame.addKeyListener(...).
The overridden keyPressed() method prints the key that was pressed.
We create a Label named “Press a key…” to display the key code.
The keyPressed() method updates the label text with the key code.We add a WindowListener using frame.addWindowListener(...).
The overridden windowClosing() method calls System.exit(0) to close the program when the window is closed.
Comments
Post a Comment