0% found this document useful (0 votes)
21 views9 pages

Java Keyboard Event Handling Basics

Uploaded by

yashhaibatpure5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views9 pages

Java Keyboard Event Handling Basics

Uploaded by

yashhaibatpure5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Java Event Handling

KeyEvent, KeyListener, KeyAdapter


Introduction
• Java uses the event handling model to interact
with the keyboard.
• Important parts: Event Classes, Event
Interfaces, and Adapter Classes.
• Keyboard events are handled using KeyEvent,
KeyListener, and KeyAdapter.
KeyEvent
• KeyEvent class describes a keyboard action.
• Belongs to [Link] package.
• Three types: keyPressed, keyReleased,
keyTyped.
• Useful methods: getKeyChar(), getKeyCode().
KeyListener
• KeyListener interface listens for keyboard
events.
• Contains 3 methods: keyPressed(),
keyReleased(), keyTyped().
• All methods must be implemented.
Example – KeyListener

import [Link].*;
import [Link].*;

class KeyListenerExample extends Frame implements KeyListener {


Label l; TextArea area;
KeyListenerExample() {
l = new Label();
[Link](20,50,200,20);
area = new TextArea();
[Link](20,80,200,100);
[Link](this);
add(l); add(area);
setSize(300,300); setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) { [Link]("Key Pressed"); }
public void keyReleased(KeyEvent e) { [Link]("Key Released"); }
public void keyTyped(KeyEvent e) { [Link]("Key Typed"); }
public static void main(String[] args) { new KeyListenerExample(); }
}
KeyAdapter
• KeyAdapter is an abstract class.
• Provides empty implementations of
KeyListener methods.
• We can extend KeyAdapter and override only
needed methods.
• Makes code shorter and cleaner.
Example – KeyAdapter

import [Link].*;
import [Link].*;

class KeyAdapterExample extends Frame {


KeyAdapterExample() {
TextArea area = new TextArea();
[Link](50,50,200,200);
[Link](new KeyAdapter() {
public void keyPressed(KeyEvent e) {
[Link]("Key Pressed: " + [Link]());
}
});
add(area);
setSize(300,300); setLayout(null);
setVisible(true);
}
public static void main(String[] args) { new KeyAdapterExample(); }
}
KeyListener vs KeyAdapter
• KeyListener: Must implement all 3 methods.
• KeyAdapter: Override only required methods.
• KeyListener: Longer code.
• KeyAdapter: Shorter code.
Conclusion
• KeyEvent: Represents keyboard actions.
• KeyListener: Handles all key events.
• KeyAdapter: Simplifies coding by selective
override.
• Together, they provide flexible keyboard input
handling.

You might also like