Java ActionListener and Event Handling Guide
Java ActionListener and Event Handling Guide
Definition:
Event handling in Java allows a program to respond to user actions like button clicks, key presses, or
mouse movements. The ActionListener interface is used to handle action events such as button clicks in
AWT or Swing applications. It contains one method, actionPerformed(ActionEvent e), which is
executed when an action occurs.
Steps to Handle Events using ActionListener:
1. Import [Link].* package.
2. Implement the ActionListener interface in your class.
3. Override the actionPerformed() method.
4. Register the listener using addActionListener() with the event source (e.g., Button).
Example Program:
import [Link].*; import [Link].*; public class ActionListenerExample extends Frame
implements ActionListener { TextField tf; Button b; ActionListenerExample() { tf = new TextField();
[Link](60, 50, 170, 20); b = new Button("Click Me"); [Link](100, 120, 80, 30);
[Link](this); // Register listener add(b); add(tf); setSize(300, 300); setLayout(null);
setVisible(true); } public void actionPerformed(ActionEvent e) { [Link]("Button Clicked!"); } public static
void main(String[] args) { new ActionListenerExample(); } }
Output:
When the user clicks the "Click Me" button, the text field displays the message: "Button Clicked!"
Key Points:
• ActionListener is used for handling button clicks and similar actions.
• The actionPerformed() method executes automatically when the event occurs.
• Multiple components can share the same listener.
• Used widely in both AWT and Swing GUI applications.
Autoboxing and Unboxing in Java
Definition:
Autoboxing is the automatic conversion by the Java compiler of a primitive type (e.g., int) into its
corresponding wrapper class object (e.g., Integer). Unboxing is the reverse — automatic conversion of a
wrapper object back to its primitive value.
Why it exists:
The Collections framework and many APIs work with objects, not primitives. Autoboxing/unboxing allows
primitives to be used where objects are required with minimal code.
Examples:
1) Autoboxing (primitive → wrapper):
int a = 10; Integer obj = a; // compiler does: [Link](a) 2) Unboxing (wrapper → primitive):
Integer obj = [Link](20); int b = obj; // compiler does: [Link]() 3) With Collections:
List list = new ArrayList<>(); [Link](5); // autoboxing from int to Integer int x = [Link](0); // unboxing from
Integer to int
Important Notes & Pitfalls:
• NullPointerException: Unboxing a null wrapper causes NPE. Example: Integer i = null; int x = i; // NPE.
• Performance: Boxing/unboxing creates objects and may affect performance. Use primitives in
performance-critical code.
• Equality: Beware of == with wrappers. Integer a = 1000, b = 1000; (a == b) may be false; use equals()
for value comparison. Note: JVM caches Integer values from -128 to 127, so == may be true for small
ints.
• Autoboxing conversions used by compiler: compiler inserts calls like [Link]() and
intValue() during boxing/unboxing.
Quick Example Program:
public class AutoBoxUnbox { public static void main(String[] args) { Integer iw = 10; // autoboxing int p =
iw + 5; // unboxing used in arithmetic [Link](p); // prints 15 Integer a = 128; Integer b = 128;
[Link](a == b); // usually false (different objects) [Link]([Link](b)); // true } }
Key Points to Remember:
• Autoboxing lets you write cleaner code when using collections/APIs that expect objects.
• Unboxing can throw NullPointerException if wrapper is null.
• Prefer primitives for heavy numeric computations; be mindful of overhead.
• Use equals() to compare wrapper values reliably.
Character Class in Java
Definition:
The Character class in Java is a wrapper class for the primitive data type char. It is part of the [Link]
package and provides several static methods to manipulate, test, and convert characters. This class is
used when working with objects instead of primitive char values, such as in Collections or Generics.
Purpose:
It allows easy handling of characters through methods that check character types, convert cases, and
handle Unicode values. It’s also useful for text processing, validation, and conversions.
Important Methods of Character Class:
Method Description Example
isLetter(char ch) Checks if the character is a letter. [Link]('A') → true
isDigit(char ch) Checks if the character is a digit. [Link]('5') → true
isWhitespace(char ch) Checks if the character is a space, tab, or newline. [Link](' ') → true
isUpperCase(char ch) Checks if the character is uppercase. [Link]('A') → true
isLowerCase(char ch) Checks if the character is lowercase. [Link]('b') → true
toUpperCase(char ch) Converts to uppercase. [Link]('a') → 'A'
toLowerCase(char ch) Converts to lowercase. [Link]('B') → 'b'
isLetterOrDigit(char ch) Checks if character is letter or digit. [Link]('A') → true
getNumericValue(char ch) Returns numeric value of a digit character. [Link]('7') → 7
compare(char x, char y) Compares two characters numerically. [Link]('A','B') → negative
Example Program:
public class CharacterExample { public static void main(String[] args) { char ch = 'a';
[Link]([Link](ch)); // true [Link]([Link](ch)); // A
[Link]([Link]('5')); // true } }
Key Points to Remember:
• Character class is immutable and part of [Link].
• Provides utility methods to test and convert characters.
• Supports Unicode, making it useful for multilingual applications.
• Frequently used for validation and parsing tasks.
• Autoboxing allows direct assignment: Character ch = 'A';
Difference Between List and Set in Java
Both List and Set are interfaces in the Java Collections Framework ([Link] package). They differ
in how they handle order, duplicates, and access to elements.
Example Program:
import [Link].*; public class ListSetExample { public static void main(String[] args) { List list = new
ArrayList<>(); [Link]("Apple"); [Link]("Banana"); [Link]("Apple"); // Duplicate allowed
[Link]("List: " + list); Set set = new HashSet<>(); [Link]("Apple"); [Link]("Banana");
[Link]("Apple"); // Duplicate ignored [Link]("Set: " + set); } } Output: List: [Apple,
Banana, Apple] Set: [Banana, Apple]
Key Points to Remember:
- List = Ordered, Duplicates Allowed
- Set = Unordered, Duplicates Not Allowed
- List supports index-based access
- Set is faster for searching (uses hashing)
- Common Implementations: ArrayList, LinkedList, HashSet, TreeSet, LinkedHashSet
Java Event Classes
Definition:
In Java, the Event Classes are part of the [Link] package and represent various types of user
interactions or system-generated events. These classes are used in the Event Delegation Model to
capture and handle events such as button clicks, key presses, mouse movements, window actions, etc.
Event Delegation Model:
This model is based on the idea that an event source generates an event and sends it to one or more
event listeners that handle the event. The listeners are registered to the source using methods like
addActionListener(), addKeyListener(), etc.
Common Event Classes in Java:
Event Class Description Example Event Source
ActionEvent Generated when a button is clicked or a menu item is
Button,
selected.
MenuItem
ItemEvent Generated when a checkbox or list item is selected/deselected.
Checkbox, Choice, List
AdjustmentEvent Occurs when the value of a scrollbar is changed. Scrollbar
TextEvent Generated when the value in a text field or area changes.
TextField, TextArea
FocusEvent Occurs when a component gains or loses focus. TextField, Button
KeyEvent Occurs when a key is pressed, released, or typed. Keyboard
MouseEvent Occurs when mouse is clicked, pressed, released, orMouse
moved.
WindowEvent Generated when a window is opened, closed, or activated.
Window, Frame, Dialog
Example Program:
import [Link].*; import [Link].*; public class EventExample extends Frame implements
ActionListener { Button b; EventExample() { b = new Button("Click Me"); [Link](this);
add(b); setSize(200, 200); setLayout(new FlowLayout()); setVisible(true); } public void
actionPerformed(ActionEvent e) { [Link]("Button Clicked!"); } public static void main(String[]
args) { new EventExample(); } }
Key Points to Remember:
• Event classes are found in the [Link] package.
• Each event class has corresponding listener interfaces like ActionListener, MouseListener, etc.
• The EventObject class is the superclass of all event classes.
• Event handling improves interactivity and GUI control in AWT/Swing applications.
• Use addXListener() methods to register listeners to event sources.
8. JCheckBox and JRadioButton in Java
Introduction:
In Java, JCheckBox and JRadioButton are part of the [Link] package used to create
interactive GUI components. They allow users to make selections within graphical user interfaces
(GUIs) in Swing-based applications.
1. JCheckBox:
A JCheckBox is a graphical component that represents an option that can be selected or
deselected. It allows multiple selections at once, meaning a user can select several checkboxes
simultaneously.
Common Methods:
- isSelected() – Returns true if the checkbox is selected.
- setSelected(boolean state) – Selects or deselects the checkbox.
- getText() – Returns the text of the checkbox.
2. JRadioButton:
A JRadioButton is used when only one option out of a group can be selected at a time. To group
multiple radio buttons together, we use the ButtonGroup class.
Common Methods:
- isSelected() – Checks if the radio button is selected.
- setSelected(boolean state) – Selects or deselects the button.
- setActionCommand(String cmd) – Sets a command string for the button.
Example Program:
import [Link].*; import [Link].*; public class CheckRadioExample { public static void
main(String[] args) { JFrame f = new JFrame("JCheckBox & JRadioButton Example"); JCheckBox
cb1 = new JCheckBox("Java"); JCheckBox cb2 = new JCheckBox("Python"); [Link](50,
50, 100, 30); [Link](50, 80, 100, 30); JRadioButton r1 = new JRadioButton("Male");
JRadioButton r2 = new JRadioButton("Female"); [Link](200, 50, 100, 30);
[Link](200, 80, 100, 30); ButtonGroup bg = new ButtonGroup(); [Link](r1); [Link](r2);
[Link](cb1); [Link](cb2); [Link](r1); [Link](r2); [Link](400, 200); [Link](null); [Link](true); }
}
Key Points:
- FlowLayout: Left to right arrangement (default for Panel).
- BorderLayout: 5 regions – North, South, East, West, Center (default for Frame).
- GridLayout: Uniform grid of rows × columns.
- CardLayout: Only one component visible at a time.
- GridBagLayout: Most flexible layout for advanced positioning.
- BoxLayout: Vertical or horizontal alignment.
Example (FlowLayout):
import [Link].*; public class FlowExample { public static void main(String[] args) { Frame f = new
Frame("FlowLayout"); [Link](new FlowLayout()); [Link](new Button("A")); [Link](new
Button("B")); [Link](200,150); [Link](true); } }
6. List Interface in Java
Definition:
The List interface in Java is part of the [Link] package and extends the Collection interface. It
represents an ordered collection of elements that allows duplicate values and provides
positional access using indexes. Lists maintain the insertion order and are widely used for storing
data dynamically.
Class Description
ArrayList Dynamic array that increases size automatically. Fast for searching and iteration.
LinkedList Doubly-linked list structure. Fast insertion and deletion operations.
Vector Synchronized dynamic array, thread-safe but slower than ArrayList.
Stack Subclass of Vector implementing LIFO (Last-In-First-Out) principle.
Example Program:
import [Link].*; public class ListExample { public static void main(String[] args) { List list = new
ArrayList<>(); [Link]("Apple"); [Link]("Banana"); [Link]("Cherry"); [Link]("Apple"); // duplicate
allowed for(String s : list) [Link](s); } } Output:
Apple
Banana
Cherry
Apple
Purpose:
- To create a thread by implementing the Runnable interface instead of extending the Thread class.
- Allows a class to extend another class while still enabling multithreading.
- Encourages better separation of task logic from thread management.
Example Program:
class MyRunnable implements Runnable { public void run() { for(int i=1; i<=5; i++) {
[Link]([Link]().getName() + " - Count: " + i); try { [Link](500); }
catch(Exception e) {} } } } public class RunnableExample { public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(), "Thread-1"); Thread t2 = new Thread(new
MyRunnable(), "Thread-2"); [Link](); [Link](); } } Output:
Thread-1 - Count: 1
Thread-2 - Count: 1
... (execution order may vary)
2. Wrapper Classes:
Wrapper classes are object representations of primitive data types. They are defined in the
[Link] package and are used for converting primitive types into objects (Autoboxing) and vice
versa (Unboxing).
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Key Points:
- Threads allow multitasking within a single program.
- Wrapper classes convert primitives into objects.
- Thread Life Cycle → New → Runnable → Running → Waiting/Blocked → Terminated.
5. Type Casting in Java
Definition:
Type casting in Java is the process of converting one data type into another. It allows a variable
of one type to be treated as another type. Type casting is mainly used when assigning values
between different data types or working with inheritance.
Example Program:
public class TypeCastingExample { public static void main(String[] args) { int a = 10; double b = a; //
Implicit Casting double x = 9.8; int y = (int) x; // Explicit Casting [Link]("Implicit: " + b);
[Link]("Explicit: " + y); } } Output:
Implicit: 10.0
Explicit: 9
Example Program:
import [Link].*; public class JDBCExample { public static void main(String[] args) throws Exception {
[Link]("[Link]"); Connection con = [Link](
"jdbc:mysql://localhost:3306/testdb", "root", "password"); // Using Statement Statement stmt =
[Link](); ResultSet rs = [Link]("SELECT * FROM employee"); while([Link]())
[Link]([Link](1) + " " + [Link](2)); // Using PreparedStatement PreparedStatement ps =
[Link]("INSERT INTO employee VALUES(?, ?)"); [Link](1, 101); [Link](2, "John");
[Link](); [Link](); } }
Key Points to Remember:
• Statement – Executes static SQL; recompiled each time.
• PreparedStatement – Precompiled and parameterized; faster execution.
• CallableStatement – Executes stored procedures and handles parameters.
• PreparedStatement and CallableStatement are preferred for performance and security.