COMPUTER PROGRAMMING II
COS 202
Learning outcomes
●
●
●
●
●
Work with procedural and object-oriented aspects of the Java
language.
Develop sound techniques for designing, developing, and documenting
well-structured programs using proper software engineering principles.
Continue to apply problem-solving skills and provide a foundation for
advanced programming courses using an object-oriented programming
(OOP) methodology.
Implement common programming algorithms for data collections for
use in further programming courses.
Develop a GUI interface and related processing for an application.
Course topics
●
●
●
●
●
Module 1: Inheritance
Module 2: Polymorphism
Module 3: Exceptions
Module 4: Introduction to Collections - Stacks
Module 5: Graphical User Interfaces
1
Module 1
Inheritance
Introduction to Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that
allows one class to inherit the properties and methods of another class. This
promotes code reusability and establishes a natural hierarchy between classes.
Objectives
By the end of this module, students should be able to:
- Understand the concept of inheritance and its importance in OOP.
- Define and implement base (parent) and derived (child) classes.
- Use the `super` keyword to access and extend the functionality of the parent
class.
- Differentiate between single, multiple, and multilevel inheritance.
- Apply inheritance to solve real-world problems.
1.1 Understanding Inheritance
1.1.1 What is Inheritance?
Inheritance is a mechanism where a new class, known as a derived or child class,
inherits attributes and methods from an existing class, known as a base or parent
class. The child class can use and modify these inherited attributes and methods
as if they were defined within the child class itself.
1.1.2 Why Use Inheritance?
- Code Reusability: Inheritance allows for the reuse of code across multiple classes
without duplication.
- Hierarchical Classification: It helps in creating a natural hierarchical classification
of classes.
- Extensibility: New functionality can be added to the inherited class without
modifying the existing code.
2
1.2 Implementing Inheritance
1.2.1 Base and Derived Classes
In Java, a class can be made to inherit from another class using the `extends`
keyword.
```java
class ParentClass {
String name;
ParentClass(String name) {
this.name = name;
}
void displayName() {
System.out.println("Name: " + name);
}
}
class ChildClass extends ParentClass {
int age;
ChildClass(String name, int age) {
super(name);
this.age = age;
}
void displayInfo() {
displayName();
System.out.println("Age: " + age);
}
public static void main(String[] args) {
ChildClass child = new ChildClass("Alice", 20);
child.displayInfo();
3
}
}
```
1.2.2 The `super` Keyword
The `super` keyword is used to call the constructor and methods of the parent
class from within the child class. This is particularly useful when the child class
needs to extend the functionality of the parent class.
```java
class ParentClass {
String name;
ParentClass(String name) {
this.name = name;
}
void displayName() {
System.out.println("Name: " + name);
}
}
class ChildClass extends ParentClass {
int age;
ChildClass(String name, int age) {
super(name);
this.age = age;
}
void displayInfo() {
super.displayName();
System.out.println("Age: " + age);
}
public static void main(String[] args) {
4
ChildClass child = new ChildClass("Alice", 20);
child.displayInfo();
}
}
```
1.3 Types of Inheritance
1.3.1 Single Inheritance
Single inheritance occurs when a class inherits from one parent class.
```java
class Parent {
void parentMethod() {
System.out.println("This is a parent method.");
}
}
class Child extends Parent {
void childMethod() {
System.out.println("This is a child method.");
}
public static void main(String[] args) {
Child child = new Child();
child.parentMethod();
child.childMethod();
}
}
```
1.3.2 Multiple Inheritance (Interface)
Java does not support multiple inheritance with classes, but it can be achieved
using interfaces.
5
```java
interface Parent1 {
void parent1Method();
}
interface Parent2 {
void parent2Method();
}
class Child implements Parent1, Parent2 {
public void parent1Method() {
System.out.println("This is parent1 method.");
}
public void parent2Method() {
System.out.println("This is parent2 method.");
}
void childMethod() {
System.out.println("This is a child method.");
}
public static void main(String[] args) {
Child child = new Child();
child.parent1Method();
child.parent2Method();
child.childMethod();
}
}
```
1.3.3 Multilevel Inheritance
Multilevel inheritance occurs when a class is derived from another derived class.
```java
class Grandparent {
6
void grandparentMethod() {
System.out.println("This is a grandparent method.");
}
}
class Parent extends Grandparent {
void parentMethod() {
System.out.println("This is a parent method.");
}
}
class Child extends Parent {
void childMethod() {
System.out.println("This is a child method.");
}
public static void main(String[] args) {
Child child = new Child();
child.grandparentMethod();
child.parentMethod();
child.childMethod();
}
}
```
1.4 Real-World Example
Let's consider a real-world example of inheritance. Suppose we have a base class
`Vehicle` and we want to create two derived classes `Car` and `Motorcycle`.
```java
class Vehicle {
String make;
String model;
Vehicle(String make, String model) {
this.make = make;
7
this.model = model;
}
void displayInfo() {
System.out.println("Make: " + make + ", Model: " + model);
}
}
class Car extends Vehicle {
int doors;
Car(String make, String model, int doors) {
super(make, model);
this.doors = doors;
}
void displayInfo() {
super.displayInfo();
System.out.println("Doors: " + doors);
}
}
class Motorcycle extends Vehicle {
String type;
Motorcycle(String make, String model, String type) {
super(make, model);
this.type = type;
}
void displayInfo() {
super.displayInfo();
System.out.println("Type: " + type);
}
public static void main(String[] args) {
Car car = new Car("Toyota", "Camry", 4);
8
Motorcycle motorcycle = new Motorcycle("Honda", "CBR", "Sport");
car.displayInfo();
motorcycle.displayInfo();
}
}
```
Summary
In this module, we have explored the concept of inheritance in OOP. We have
learned how to implement inheritance in Java, the different types of inheritance,
and seen a real-world example of how inheritance can be applied. Mastering
inheritance allows you to create more flexible, reusable, and organized code.
Exercises
1. Create a base class `Animal` with methods `eat` and `sleep`. Create a derived
class `Dog` that adds a method `bark`. Instantiate an object of the `Dog` class and
call all three methods.
2. Implement a class hierarchy for an e-commerce system with base class
`Product` and derived classes `Book` and `Electronics`. Include attributes and
methods relevant to each class.
Module 2: Polymorphism
Introduction to Polymorphism
Polymorphism is a core concept in object-oriented programming (OOP) that
allows objects of different classes to be treated as objects of a common
superclass. It is the ability of a single function or method to work in different ways
based on the object it is acting upon. This promotes flexibility and maintainability
in code.
Objectives
9
By the end of this module, students should be able to:
- Understand the concept of polymorphism and its importance in OOP.
- Implement method overriding to achieve runtime polymorphism.
- Implement method overloading to achieve compile-time polymorphism.
- Use polymorphism to write more flexible and reusable code.
2.1 Understanding Polymorphism
2.1.1 What is Polymorphism?
Polymorphism means "many forms." In the context of OOP, it allows methods to
do different things based on the object it is acting upon, even though they share
the same name.
2.1.2 Why Use Polymorphism?
- Flexibility: Polymorphism allows for the creation of flexible and reusable code.
- Maintainability: It makes code easier to maintain and extend.
- Simplification: It simplifies code by allowing the same method to be used on
different types of objects.
2.2 Types of Polymorphism
2.2.1 Compile-Time Polymorphism (Method Overloading)
Compile-time polymorphism, also known as method overloading, occurs when
multiple methods have the same name but different parameters (different type
or number of parameters). The appropriate method is selected at compile time.
```java
class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers
10
int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two double values
double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
MathOperations math = new MathOperations();
System.out.println("Sum of 2 and 3: " + math.add(2, 3));
System.out.println("Sum of 1, 2, and 3: " + math.add(1, 2, 3));
System.out.println("Sum of 2.5 and 3.5: " + math.add(2.5, 3.5));
}
}
```
2.2.2 Runtime Polymorphism (Method Overriding)
Runtime polymorphism, also known as method overriding, occurs when a
subclass provides a specific implementation of a method that is already defined in
its superclass. The method to be called is determined at runtime based on the
object being referred to.
```java
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
11
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows");
}
}
class TestPolymorphism {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Animal reference and object
Animal myDog = new Dog();
// Animal reference but Dog object
Animal myCat = new Cat();
// Animal reference but Cat object
myAnimal.sound(); // Outputs: Animal makes a sound
myDog.sound(); // Outputs: Dog barks
myCat.sound(); // Outputs: Cat meows
}
}
```
2.3 Using Polymorphism in Real-World Applications
2.3.1 Polymorphism in User Interfaces
Polymorphism is often used in graphical user interfaces (GUIs) where different
components (buttons, text fields, labels) can be treated as instances of the same
superclass (Component).
```java
class Component {
void draw() {
System.out.println("Drawing a component");
}
}
12
class Button extends Component {
@Override
void draw() {
System.out.println("Drawing a button");
}
}
class TextField extends Component {
@Override
void draw() {
System.out.println("Drawing a text field");
}
}
class Label extends Component {
@Override
void draw() {
System.out.println("Drawing a label");
}
}
class TestGUI {
public static void main(String[] args) {
Component[] components = {new Button(), new TextField(), new Label()};
for (Component component : components) {
component.draw();
}
}
}
```
2.3.2 Polymorphism in E-Commerce Systems
In an e-commerce system, polymorphism can be used to handle different types of
payments (credit card, PayPal, bank transfer) using a common interface.
```java
13
interface Payment {
void processPayment();
}
class CreditCardPayment implements Payment {
@Override
public void processPayment() {
System.out.println("Processing credit card payment");
}
}
class PayPalPayment implements Payment {
@Override
public void processPayment() {
System.out.println("Processing PayPal payment");
}
}
class BankTransferPayment implements Payment {
@Override
public void processPayment() {
System.out.println("Processing bank transfer payment");
}
}
class TestPayment {
public static void main(String[] args) {
Payment payment1 = new CreditCardPayment();
Payment payment2 = new PayPalPayment();
Payment payment3 = new BankTransferPayment();
payment1.processPayment();
payment2.processPayment();
payment3.processPayment();
}
Summary
14
In this module, we have explored the concept of polymorphism in OOP. We have
learned how to implement both compile-time and runtime polymorphism in Java,
and seen real-world examples of how polymorphism can be applied. Mastering
polymorphism allows you to create more flexible, maintainable, and reusable
code.
Exercises
1. Create a base class `Shape` with a method `draw`. Create derived
classes `Circle`, `Rectangle`, and `Triangle`, each overriding the `draw`
method. Instantiate objects of each class and call their `draw`
methods.
2. Implement an interface `Animal` with a method `makeSound`.
Create classes `Cow`, `Duck`, and `Sheep` that implement the
`Animal` interface. Instantiate objects of each class and call their
`makeSound` methods.
Module 3: Exceptions
Introduction to Exceptions
Exceptions are events that disrupt the normal flow of a program's execution. They
are typically used to handle errors or other exceptional conditions that occur
during runtime. Proper exception handling is crucial for building robust and errorresistant programs.
Objectives
By the end of this module, students should be able to:
- Understand what exceptions are and why they are important.
- Differentiate between checked and unchecked exceptions.
- Use try, catch, finally blocks to handle exceptions.
- Create custom exceptions.
- Apply best practices for exception handling.
15
3.1 Understanding Exceptions
3.1.1 What are Exceptions?
An exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions. Exceptions can be caused by a variety of
factors, such as invalid user input, file not found, network errors, or division by
zero.
3.1.2 Why Use Exception Handling?
- Robustness: Proper exception handling allows a program to deal with
unexpected situations without crashing.
- Debugging: Exceptions provide a way to report error conditions in a controlled
manner.
- Separation of Error Handling: It separates the error handling code from the
regular code, making the program easier to read and maintain.
3.2 Types of Exceptions
3.2.1 Checked Exceptions
Checked exceptions are exceptions that are checked at compile-time. These
exceptions must be either caught or declared in the method signature using the
`throws` keyword.
```java
import java.io.*;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
FileReader file = new FileReader("nonexistentfile.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
16
}
}
```
3.2.2 Unchecked Exceptions
Unchecked exceptions are exceptions that are not checked at compile-time.
These exceptions are typically caused by programming errors, such as logic errors
or improper use of an API.
```java
public class UncheckedExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic error: " + e.getMessage());
}
}
}
```
3.3 Handling Exceptions
3.3.1 The try-catch Block
The `try` block contains code that might throw an exception. The `catch` block
contains code to handle the exception.
```java
public class TryCatchExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
}
17
}
}
```
3.3.2 The finally Block
The `finally` block contains code that is always executed, regardless of whether an
exception is thrown or not. It is typically used for cleanup activities, such as
closing files or releasing resources.
```java
public class FinallyExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
} finally {
System.out.println("This will always be executed.");
}
}
}
```
3.4 Creating Custom Exceptions
3.4.1 Defining a Custom Exception
You can create your own exception class by extending the `Exception` class for
checked exceptions or the `RuntimeException` class for unchecked exceptions.
```java
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
18
public class CustomExceptionExample {
public static void main(String[] args) {
try {
validateAge(15);
} catch (CustomException e) {
System.out.println("Caught custom exception: " + e.getMessage());
}
}
static void validateAge(int age) throws CustomException {
if (age < 18) {
throw new CustomException("Age must be 18 or older.");
}
}
}
```
3.5 Best Practices for Exception Handling
1. Catch Specific Exceptions: Always catch specific exceptions rather than a
general `Exception`. This makes the code clearer and easier to debug.
2. Use Finally for Cleanup: Use the `finally` block to clean up resources, such
as closing files or releasing network connections.
3. Don't Suppress Exceptions: Avoid using empty catch blocks. Always handle
exceptions appropriately or rethrow them.
4. Document Exception Handling: Use JavaDoc to document the exceptions a
method might throw.
5. Log Exceptions: Log exceptions to help diagnose issues when they occur in
production environments.
Summary
19
In this module, we have explored the concept of exceptions in Java. We have
learned about the different types of exceptions, how to handle them using try,
catch, and finally blocks, and how to create custom exceptions. Mastering
exception handling allows you to write more robust and error-resistant programs.
Exercises
1. Write a Java program that reads a file and handles potential exceptions
such as `FileNotFoundException` and `IOException`.
2. Create a custom exception `InvalidInputException` and use it to handle
invalid user input in a Java program.
3. Implement a program that demonstrates the use of multiple catch blocks to
handle different types of exceptions.
Module 4: Introduction to Collections - Stacks
Introduction to Collections
In Java, collections are frameworks that provide an architecture to store and
manipulate groups of objects. They provide various operations such as searching,
sorting, insertion, manipulation, and deletion. This module focuses on one
specific type of collection: Stacks.
Objectives
By the end of this module, students should be able to:
- Understand the concept and usage of collections in Java.
- Comprehend the stack data structure and its operations.
- Implement stack operations using the `Stack` class in Java.
- Apply stacks in solving real-world problems.
4.1 Understanding Collections
20
4.1.1 What are Collections?
Collections are objects that group multiple elements into a single unit. They are
used to store, retrieve, manipulate, and communicate aggregate data. Collections
are essential in Java for handling dynamic data structures, such as lists, sets,
queues, and stacks.
4.1.2 Why Use Collections?
- Efficiency: Collections provide efficient data storage and manipulation.
- Reusability: They offer reusable data structures.
- Flexibility: Collections can dynamically grow or shrink in size.
4.2 The Stack Data Structure
4.2.1 What is a Stack?
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle.
The last element added to the stack is the first one to be removed. Stacks are
used in various applications, such as function call management in programming,
undo mechanisms in text editors, and parsing expressions in compilers.
4.2.2 Basic Operations on a Stack
-Push: Add an element to the top of the stack.
- Pop: Remove and return the top element of the stack.
- Peek: Return the top element without removing it.
- isEmpty: Check if the stack is empty.
- Size: Return the number of elements in the stack.
4.3 Implementing a Stack in Java
4.3.1 Using the `Stack` Class
Java provides a built-in `Stack` class that extends the `Vector` class and
implements the `List` interface. Here's how you can use the `Stack` class:
21
```java
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
// Push elements onto the stack
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Stack: " + stack);
// Pop elements from the stack
int removedElement = stack.pop();
System.out.println("Popped element: " + removedElement);
System.out.println("Stack after pop: " + stack);
// Peek at the top element
int topElement = stack.peek();
System.out.println("Top element: " + topElement);
// Check if the stack is empty
boolean isEmpty = stack.isEmpty();
System.out.println("Is stack empty? " + isEmpty);
// Get the size of the stack
int size = stack.size();
System.out.println("Stack size: " + size);
}
}
```
4.3.2 Custom Stack Implementation
22
You can also create your own stack implementation using arrays or linked lists.
Here’s a simple example using an array:
```java
class CustomStack {
private int maxSize;
private int[] stackArray;
private int top;
public CustomStack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
public void push(int value) {
if (top == maxSize - 1) {
System.out.println("Stack is full!");
} else {
stackArray[++top] = value;
}
}
public int pop() {
if (top == -1) {
System.out.println("Stack is empty!");
return -1;
} else {
return stackArray[top--];
}
}
public int peek() {
if (top == -1) {
System.out.println("Stack is empty!");
return -1;
} else {
23
return stackArray[top];
}
}
public boolean isEmpty() {
return (top == -1);
}
public int size() {
return top + 1;
}
public static void main(String[] args) {
CustomStack stack = new CustomStack(3);
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Top element: " + stack.peek());
System.out.println("Stack size: " + stack.size());
stack.pop();
System.out.println("Top element after pop: " + stack.peek());
System.out.println("Stack size after pop: " + stack.size());
stack.pop();
stack.pop();
stack.pop(); // Attempt to pop from an empty stack
}
}
```
4.4 Applications of Stacks
24
4.4.1 Expression Evaluation
Stacks are widely used in evaluating arithmetic expressions, particularly in
converting infix expressions to postfix expressions (Reverse Polish Notation) and
then evaluating them.
4.4.2 Function Call Management
The call stack is used to manage function calls and local variables in most
programming languages, ensuring that each function call is completed before the
next one begins.
4.4.3 Undo Mechanisms
Text editors and other applications use stacks to implement undo functionality.
Each change is pushed onto the stack, and popping the stack reverts to the
previous state.
4.4.4 Parsing
Compilers use stacks to parse expressions, ensuring that parentheses and other
delimiters are balanced.
Summary
In this module, we have explored the concept of collections in Java, focusing on
the stack data structure. We have learned about the basic operations of a stack,
how to implement a stack using the `Stack` class, and how to create a custom
stack implementation. We also discussed various applications of stacks in realworld scenarios. Mastering stacks is essential for understanding more complex
data structures and algorithms.
Exercises
25
1. Write a Java program that uses a stack to reverse a string.
2. Implement a stack using a linked list instead of an array.
3. Create a stack-based application that checks for balanced parentheses in an
expression.
4. Modify the custom stack implementation to handle generic types.
Module 5: Graphical User Interfaces (GUIs)
Introduction to GUIs
Graphical User Interfaces (GUIs) allow users to interact with programs visually
through graphical elements like windows, buttons, text fields, and more. Unlike
command-line interfaces, GUIs provide an intuitive and user-friendly way to
interact with software applications.
Objectives
By the end of this module, students should be able to:
- Understand the basics of GUI development.
- Create simple GUI applications using Java's Swing library.
- Use common GUI components such as buttons, labels, text fields, and panels.
- Handle user events to make applications interactive.
5.1 Introduction to Java Swing
5.1.1 What is Swing?
Swing is a part of Java Foundation Classes (JFC) used to create window-based
applications. It is built on top of the Abstract Window Toolkit (AWT) and provides
a more comprehensive set of GUI components.
5.1.2 Why Use Swing?
26
- Platform Independence: Swing provides a consistent look and feel across
different platforms.
- Rich Set of Components: Swing includes advanced components like tables, trees,
sliders, and more.
- Customizable: Swing components are highly customizable, allowing developers
to create visually appealing interfaces.
5.2 Creating a Simple GUI Application
5.2.1 Setting Up the Environment
To start building GUI applications with Swing, ensure you have a Java
Development Kit (JDK) installed and a development environment like IntelliJ IDEA,
Eclipse, or NetBeans.
5.2.2 A Basic Swing Application
Here’s a simple example of a Swing application that creates a window with a
label:
```java
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class SimpleGUI {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Simple GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
JLabel label = new JLabel("Hello, Swing!", JLabel.CENTER);
frame.add(label);
frame.setVisible(true);
});
27
}
}
```
5.2.3 Understanding the Code
- JFrame: Represents the main window of the application.
- JLabel: A simple component that displays a text string.
- SwingUtilities.invokeLater: Ensures that the GUI creation and updates are
performed on the Event Dispatch Thread (EDT).
5.3 Common GUI Components
5.3.1 Buttons
Buttons are used to perform actions when clicked by the user.
```java
import javax.swing.JButton;
public class ButtonExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Button Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
JButton button = new JButton("Click Me!");
button.addActionListener(e -> System.out.println("Button clicked!"));
frame.add(button);
frame.setVisible(true);
});
}
}
```
28
5.3.2 Text Fields
Text fields allow users to enter and edit text.
```java
import javax.swing.JTextField;
public class TextFieldExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Text Field Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
JTextField textField = new JTextField(20);
frame.add(textField);
frame.setVisible(true);
});
}
}
```
5.3.3 Panels
Panels are containers that hold and organize other components.
```java
import javax.swing.JPanel;
public class PanelExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Panel Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
29
JPanel panel = new JPanel();
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
frame.add(panel);
frame.setVisible(true);
});
}
}
```
5.4 Event Handling
5.4.1 Action Listeners
Action listeners are used to handle events, such as button clicks.
```java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionListenerExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Action Listener Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
JButton button = new JButton("Click Me!");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
frame.add(button);
30
frame.setVisible(true);
});
}
}
```
5.4.2 Lambda Expressions
In Java 8 and later, lambda expressions can be used to simplify event handling
code.
```java
public class LambdaExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Lambda Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
JButton button = new JButton("Click Me!");
button.addActionListener(e -> System.out.println("Button clicked!"));
frame.add(button);
frame.setVisible(true);
});
}
}
```
## 5.5 Creating a More Complex GUI Application
### 5.5.1 Combining Components
```java
import javax.swing.*;
public class ComplexGUI {
public static void main(String[] args) {
31
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Complex GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
JPanel panel = new JPanel();
panel.add(new JLabel("Enter your name:"));
JTextField textField = new JTextField(15);
panel.add(textField);
JButton button = new JButton("Submit");
panel.add(button);
JLabel resultLabel = new JLabel();
panel.add(resultLabel);
button.addActionListener(e -> {
String name = textField.getText();
resultLabel.setText("Hello, " + name + "!");
});
frame.add(panel);
frame.setVisible(true);
});
}
}
```
Summary
In this module, we have explored the basics of creating graphical user interfaces
using Java Swing. We have learned about various Swing components like buttons,
labels, text fields, and panels. We have also seen how to handle user events to
make our applications interactive. Mastering these basics will help you build more
complex and user-friendly applications.
Exercises
32
1. Create a simple calculator GUI that can perform basic arithmetic operations
(addition, subtraction, multiplication, division).
2. Design a login form with fields for username and password, and a submit
button.
3. Implement a GUI application that allows users to input and display a list of
their favorite books.
33
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )