Unit-4: Java Event Handling (5-Mark Answers)
1. Define the term event. What are the event sources? Explain the delegation event model.
Event: An event is an action or occurrence generated through user or system interaction in a GUI
program (e.g., mouse click, key press).
Event Sources: Button, TextField, CheckBox, Window, Mouse, Keyboard, MenuItem, etc.
Delegation Event Model:
- Event Source generates events.
- Event Object contains details.
- Event Listener handles events.
- The source delegates the event to the listener. It separates event creation from handling.
2. What are various types of events in [Link]?
Main event types:
- ActionEvent: Generated by Button, MenuItem, TextField.
- MouseEvent: Mouse click, press, release, enter, exit.
- MouseMotionEvent: Mouse moved or dragged.
- KeyEvent: Key press, release, typed.
- ItemEvent: Checkbox/Choice selection change.
- WindowEvent: Window open, close, minimize, activate.
- ComponentEvent: Resize, move, hide, show.
- TextEvent: Text changes in TextComponent.
3. What are the various adapter classes that implement commonly used listener interfaces?
Adapter classes provide empty implementations.
- WindowAdapter – implements WindowListener.
- MouseAdapter – implements MouseListener.
- MouseMotionAdapter – implements MouseMotionListener.
- KeyAdapter – implements KeyListener.
- ComponentAdapter – implements ComponentListener.
4. Explain the following.
a) Handling mouse events:
Use MouseListener and MouseMotionListener.
MouseListener methods: mouseClicked(), mousePressed(), mouseReleased(), mouseEntered(),
mouseExited().
MouseMotionListener: mouseMoved(), mouseDragged().
Register using addMouseListener() and addMouseMotionListener().
b) Layout Manager:
Controls component size and position.
Types: FlowLayout, BorderLayout, GridLayout, CardLayout.
5. Write a Java Program to handle various keyboard events.
(Program included in previous response; PDF summarizes the concept.)
Use KeyListener with methods keyPressed(), keyReleased(), keyTyped().
6. What is the role of event listeners in event handling? List the Java event listeners.
Role:
- Capture and process events.
- Provide methods to handle user actions.
- Separate UI from event logic.
Java Listeners:
ActionListener, ItemListener, KeyListener, MouseListener, MouseMotionListener, WindowListener,
TextListener, ComponentListener, FocusListener, AdjustmentListener.
7. Discuss various AWT containers with examples.
Containers:
- Panel: Simple container.
- Frame: Top-level window.
- Window: Borderless window.
- Dialog: Popup window.
- Applet: Runs inside browser.
Used to hold and manage GUI components.
8. Illustrate MouseMotionListener with a Java program.
Handles mouseMoved() and mouseDragged().
Tracks coordinates and repaints.
9. Discuss Flow and Grid Layout managers.
FlowLayout:
- Components arranged left to right.
- Moves to next row automatically.
GridLayout:
- Divides area into rows and columns.
- All cells equal size; good for structured forms/layouts.