Mastering Java Core Concepts: Generics, Collections, Events, and Swing

Classified in Computers

Written on in English with a size of 6.82 KB

Java Generics: Methods and Classes

Java Generics enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety, which allows programmers to catch invalid types at compile time, preventing runtime errors.

Generics Example: ArrayList

Consider the following example demonstrating generics with an ArrayList:

1. import java.util.*;
2. class TestGenerics1 {
3.   public static void main(String args[]) {
4.     ArrayList<String> list = new ArrayList<String>();
5.     list.add("rahul");
6.     list.add("jai");
7.     // list.add(32); // compile-time error if uncommented
8.     String s = list.get(1); // type casting is not required
9.     System.out.println("element is: " + s);
10.
11.     Iterator<String> itr = list.iterator();
12.     while (itr.hasNext()) {
13.       System.out.println(itr.next());
14.     }
15.   }
16. }

Output:

element is: jai
rahul
jai

Java Collections Framework (JCF)

The Java Collections Framework (JCF) is a set of classes and interfaces that implement commonly reusable collection data structures. Although referred to as a framework, it functions more like a library. The JCF provides both interfaces that define various collections and classes that implement them.

Using Collections.asLifoQueue

Here's an example demonstrating the use of Collections.asLifoQueue to create a LIFO (Last-In, First-Out) queue from a Deque:

1. import java.util.ArrayDeque;
2. import java.util.Collections;
3. import java.util.Deque;
4. import java.util.Queue;
5. public class CollectionAsLifoQueue {
6.   public static void main(String args[]) {
7.     Deque<String> dq = new ArrayDeque<String>(5);
8.     dq.add("java");
9.     dq.add("c");
10.    dq.add("c++");
11.    dq.add("unix");
12.    dq.add("perl");
13.    Queue<String> q = Collections.asLifoQueue(dq);
14.    System.out.println("returned queue is: " + q);
15.  }
16. }

Output:

returned queue is: [java, c, c++, unix, perl]

Java Collections: The List Interface

The java.util.List interface is a subtype of the java.util.Collection interface. It represents an ordered list of objects, meaning you can access the elements of a List in a specific order, and by an index. You can also add the same element more than once to a List.

Key characteristics of the List interface include:

  • Ordered Collection: Elements maintain their insertion order.
  • Indexed Access: Elements can be accessed by their integer index.
  • Allows Duplicates: The same element can be added multiple times.

List Example: ArrayList Operations

This example demonstrates basic operations with an ArrayList, which implements the List interface:

1. import java.util.*;
2. public class ListExample {
3.   public static void main(String args[]) {
4.     ArrayList<String> al = new ArrayList<String>();
5.     al.add("Amit");
6.     al.add("Vijay");
7.     al.add("Kumar");
8.     al.add(1, "Sachin"); // Add "Sachin" at index 1
9.     System.out.println("Element at 2nd position: " + al.get(2));
10.    for (String s : al) {
11.      System.out.println(s);
12.    }
13.  }
14. }

Output:

Element at 2nd position: Vijay
Amit
Sachin
Vijay
Kumar

Java Event Handling: Events and Listeners

In Java, an event is an object that describes a state change in a source. For example, clicking a button or dragging a mouse are events. The java.awt.event package provides many event classes and listener interfaces for handling these events.

The core components of event handling are:

  • Event Source: The component that generates the event (e.g., a button).
  • Event Object: An object that encapsulates information about the event.
  • Event Listener: An object that "listens" for events and responds when they occur.

AWT Event Handling Example

This example demonstrates a simple AWT application with a button and a text field, handling a button click event:

1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent extends Frame implements ActionListener {
4.   TextField tf;
5.   AEvent() {
6.     // Create components
7.     tf = new TextField();
8.     tf.setBounds(60, 50, 170, 20);
9.     Button b = new Button("click me");
10.    b.setBounds(100, 120, 80, 30);
11.
12.    // Register listener
13.    b.addActionListener(this); // Passing current instance
14.
15.    // Add components and set size, layout, and visibility
16.    add(b);
17.    add(tf);
18.    setSize(300, 300);
19.    setLayout(null);
20.    setVisible(true);
21.  }
22.  public void actionPerformed(ActionEvent e) {
23.    tf.setText("Welcome");
24.  }
25.  public static void main(String args[]) {
26.    new AEvent();
27.  }
28. }

Java Swing: Building Window Applications

Java Swing is a part of the Java Foundation Classes (JFC) used to create window-based applications. It is built on top of the AWT (Abstract Windowing Toolkit) API and is entirely written in Java. Unlike AWT, Java Swing provides platform-independent and lightweight components, offering a richer and more flexible set of UI elements.

The javax.swing package provides classes for the Java Swing API, such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser, and many more.

Simple Swing Example: JFrame and JButton

Let's look at a simple Swing example where we create a button and add it to a JFrame object within the main() method.

File: FirstSwingExample.java

1. import javax.swing.*;
2. public class FirstSwingExample {
3.   public static void main(String[] args) {
4.     JFrame f = new JFrame(); // Creating instance of JFrame
5.     JButton b = new JButton("click"); // Creating instance of JButton
6.     b.setBounds(130, 100, 100, 40); // x axis, y axis, width, height
7.     f.add(b); // Adding button to JFrame
8.     f.setSize(400, 500); // 400 width and 500 height
9.     f.setLayout(null); // Using no layout managers
10.    f.setVisible(true); // Making the frame visible
11.  }
12. }

Related entries: