UNIT- 3
GUI Design
Applets specific methods & Related HTML references, Applet Lifecycle, crea ng an Applet,
displaying it using Web Browser with appletwiewer.exe, Applet v/s Applica ons.
Containers
Containers, Frames and Panels, Layout Managers. Border layout, Flow layout, Grid layout,
AWT all components, Event delega on Model, Event Listeners, Swing Components.
Java Database Connec vity
Establishing a Connec on, Transac ons with Database, An Overview of RMI Applica ons,
Remote Classes and Interfaces, RMI Architecture, RMI Object Hierarchy, Security, Java
Servlets, Servlet Life Cycle, Get and Post Methods, Session Handling, Java Beans.
TOPICS TO BE COVERED
GUI Design in Java
GUI (Graphical User Interface) Design in Java is about crea ng visual apps—like windows,
bu ons, and text boxes—that users can interact with. It’s like designing a game controller
with bu ons and screens to make it easy to use.
1. Applets Specific Methods & Related HTML References
What Are Applets?
o Applets are small Java programs that run inside a web browser.
o Example: A mini calculator on a webpage is an applet.
Applet-Specific Methods:
o Applets have special methods to control their behavior:
init(): Runs when the applet starts (like se ng up the calculator).
start(): Runs a er init() to start the applet (like turning the calculator
on).
stop(): Runs when the applet is paused (like pausing the calculator).
destroy(): Runs when the applet is closed (like shu ng down the
calculator).
paint(Graphics g): Draws things on the screen (like showing numbers
on the calculator).
Related HTML References:
o To show an applet on a webpage, you use an <applet> tag in HTML.
o Example:
html
Copy
<html>
<body>
<applet code="MyApplet.class" width="200" height="200"></applet>
</body>
</html>
o Here, code is the applet file, width and height set the size.
2. Applet Lifecycle
What is the Applet Lifecycle?
o It’s the steps an applet goes through from start to finish.
Steps:
1. Ini aliza on (init()): The applet is born—like se ng up the basics.
2. Star ng (start()): The applet starts working—like showing on the screen.
3. Running: The applet does its job—like le ng you click bu ons.
4. Stopping (stop()): The applet pauses when you leave the webpage.
5. Destroying (destroy()): The applet is removed when you close the browser.
Example:
java
Copy
import java.applet.Applet;
import java.awt.Graphics;
public class MyApplet extends Applet {
public void init() {
System.out.println("Applet is star ng!");
public void start() {
System.out.println("Applet is running!");
public void stop() {
System.out.println("Applet is paused!");
public void destroy() {
System.out.println("Applet is closing!");
public void paint(Graphics g) {
g.drawString("Hello, Applet!", 50, 50);
o Output in browser: Hello, Applet! (plus console messages for each step).
3. Crea ng an Applet
How to Create an Applet?
o Write a Java class that extends Applet and use methods like paint().
Example:
java
Copy
import java.applet.Applet;
import java.awt.Graphics;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Welcome to Java Applet!", 20, 20);
Steps:
1. Save this as SimpleApplet.java.
2. Compile it: javac SimpleApplet.java (creates SimpleApplet.class).
3. Create an HTML file to show the applet:
html
Copy
<html>
<body>
<applet code="SimpleApplet.class" width="300" height="100"></applet>
</body>
</html>
4. Save the HTML as applet.html.
4. Displaying It Using Web Browser with appletviewer.exe
What is appletviewer.exe?
o It’s a tool in Java to test applets without a browser.
How to Use It?
o A er crea ng the applet and HTML file, run this command:
text
Copy
appletviewer applet.html
o This will show the applet in a small window.
Why Use It?
o It’s faster for tes ng than opening a browser.
Note: Modern browsers don’t support applets anymore, so appletviewer is useful for
learning.
5. Applet vs Applica ons
Applet:
o Runs in a browser.
o Needs HTML to display.
o Limited access to the computer (for safety).
o Example: A small game on a webpage.
Applica on:
o Runs on your computer directly.
o Doesn’t need a browser.
o Full access to the computer.
o Example: A calculator app on your desktop.
Code Difference:
o Applet: Extends Applet, uses paint().
o Applica on: Has main() method.
o Example (Applica on):
java
Copy
public class MyApp {
public sta c void main(String[] args) {
System.out.println("This is an applica on!");
Containers in Java
Containers are like boxes in Java that hold GUI components (like bu ons, text fields). They
help you organize the layout of your app.
1. Containers, Frames, and Panels
What Are Containers?
o Containers are classes that hold other GUI components.
o Example: A container is like a tray holding bu ons and labels.
Frames:
o A Frame is a top-level container (like a window) in AWT (Abstract Window
Toolkit).
o Example: When you open a calculator app, the window you see is a Frame.
Panels:
o A Panel is a smaller container inside a Frame. It groups components together.
o Example: In a calculator, the bu ons might be on a Panel inside the Frame.
Example:
java
Copy
import java.awt.*;
public class FramePanelExample {
public sta c void main(String[] args) {
Frame frame = new Frame("My Window");
frame.setSize(300, 200);
Panel panel = new Panel();
Bu on bu on = new Bu on("Click Me");
panel.add(bu on);
frame.add(panel);
frame.setVisible(true);
o Output: A window (Frame) with a bu on on a Panel.
2. Layout Managers
What Are Layout Managers?
o These are tools that decide how components (like bu ons) are arranged in a
container.
o Example: It’s like arranging furniture in a room—some layouts make it neat,
others spread things out.
Border Layout:
o Divides the container into 5 areas: North, South, East, West, Center.
o Example: A webpage with a header (North), footer (South), and content
(Center).
o Code:
java
Copy
import java.awt.*;
public class BorderLayoutExample {
public sta c void main(String[] args) {
Frame frame = new Frame("Border Layout");
frame.setSize(300, 200);
frame.setLayout(new BorderLayout());
frame.add(new Bu on("North"), BorderLayout.NORTH);
frame.add(new Bu on("South"), BorderLayout.SOUTH);
frame.add(new Bu on("Center"), BorderLayout.CENTER);
frame.setVisible(true);
o Output: A window with bu ons in North, South, and Center.
Flow Layout:
o Places components in a row, le to right. If there’s no space, it moves to the
next row.
o Example: Like arranging books on a shelf—when one row is full, start the
next.
o Code:
java
Copy
import java.awt.*;
public class FlowLayoutExample {
public sta c void main(String[] args) {
Frame frame = new Frame("Flow Layout");
frame.setSize(300, 200);
frame.setLayout(new FlowLayout());
frame.add(new Bu on("Bu on 1"));
frame.add(new Bu on("Bu on 2"));
frame.add(new Bu on("Bu on 3"));
frame.setVisible(true);
o Output: Bu ons in a row.
Grid Layout:
o Arranges components in a grid (rows and columns), like a chessboard.
o Example: A c-tac-toe board with 3x3 boxes.
o Code:
java
Copy
import java.awt.*;
public class GridLayoutExample {
public sta c void main(String[] args) {
Frame frame = new Frame("Grid Layout");
frame.setSize(300, 200);
frame.setLayout(new GridLayout(2, 2)); // 2 rows, 2 columns
frame.add(new Bu on("1"));
frame.add(new Bu on("2"));
frame.add(new Bu on("3"));
frame.add(new Bu on("4"));
frame.setVisible(true);
o Output: A 2x2 grid with bu ons.
3. AWT All Components
What is AWT?
o AWT (Abstract Window Toolkit) is Java’s library for GUI components.
Common AWT Components:
o Bu on: A clickable bu on.
o Label: Shows text (not editable).
o TextField: A box to type text.
o Checkbox: A box to check or uncheck.
o Choice: A dropdown menu.
o Example:
java
Copy
import java.awt.*;
public class AWTComponentsExample {
public sta c void main(String[] args) {
Frame frame = new Frame("AWT Example");
frame.setSize(300, 200);
frame.setLayout(new FlowLayout());
frame.add(new Label("Name:"));
frame.add(new TextField(10));
frame.add(new Bu on("Submit"));
frame.add(new Checkbox("Student"));
Choice choice = new Choice();
choice.add("Op on 1");
choice.add("Op on 2");
frame.add(choice);
frame.setVisible(true);
o Output: A window with a label, text field, bu on, checkbox, and dropdown.
4. Event Delega on Model
What is This?
o It’s how Java handles user ac ons (events) like clicking a bu on.
o Example: When you click a bu on, Java listens and does something (like
showing a message).
How It Works:
o Event Source: The component (e.g., a bu on).
o Event Listener: A class that listens for the event (e.g., a click).
o Event Object: Info about the event (e.g., which bu on was clicked).
Example:
java
Copy
import java.awt.*;
import java.awt.event.*;
public class EventExample {
public sta c void main(String[] args) {
Frame frame = new Frame("Event Example");
frame.setSize(300, 200);
frame.setLayout(new FlowLayout());
Bu on bu on = new Bu on("Click Me");
bu on.addAc onListener(new Ac onListener() {
public void ac onPerformed(Ac onEvent e) {
System.out.println("Bu on clicked!");
});
frame.add(bu on);
frame.setVisible(true);
o Output: When you click the bu on, it prints Bu on clicked!.
5. Event Listeners
What Are Event Listeners?
o These are classes that “listen” for user ac ons and respond.
Common Listeners:
o Ac onListener: For bu on clicks.
o MouseListener: For mouse clicks or movement.
o KeyListener: For keyboard typing.
Example (Mouse Listener):
java
Copy
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample {
public sta c void main(String[] args) {
Frame frame = new Frame("Mouse Listener");
frame.setSize(300, 200);
frame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at: " + e.getX() + ", " + e.getY());
});
frame.setVisible(true);
o Output: Clicking in the window prints the mouse posi on.
6. Swing Components
What is Swing?
o Swing is a newer GUI library in Java (be er than AWT).
o Example: It’s like using a modern phone instead of an old one—be er
features.
Common Swing Components:
o JFrame: A window (like Frame in AWT).
o JBu on: A bu on.
o JLabel: A label.
o JTextField: A text box.
o JComboBox: A dropdown.
Example:
java
Copy
import javax.swing.*;
public class SwingExample {
public sta c void main(String[] args) {
JFrame frame = new JFrame("Swing Example");
frame.setSize(300, 200);
frame.setLayout(new java.awt.FlowLayout());
frame.add(new JLabel("Name:"));
frame.add(new JTextField(10));
frame.add(new JBu on("Submit"));
frame.setDefaultCloseOpera on(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
o Output: A window with a label, text field, and bu on (looks more modern
than AWT).
Java Database Connec vity (JDBC)
JDBC (Java Database Connec vity) is how Java talks to a database—like saving or reading
data from a table.
1. Establishing a Connec on
What is This?
o It’s how Java connects to a database to work with it.
Steps:
1. Load the database driver (like a key to open the database).
2. Connect using a URL, username, and password.
Example (Using MySQL):
java
Copy
import java.sql.*;
public class JDBCConnec on {
public sta c void main(String[] args) {
try {
// Load driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to database
Connec on con = DriverManager.getConnec on(
"jdbc:mysql://localhost:3306/mydb", "root", "password");
System.out.println("Connected to database!");
con.close();
} catch (Excep on e) {
System.out.println("Error: " + e);
o Output: Connected to database!
2. Transac ons with Database
What Are Transac ons?
o These are tasks you do with the database, like saving or reading data.
Common Tasks:
o Insert: Add new data.
o Select: Read data.
o Update: Change data.
o Delete: Remove data.
Example (Insert and Select):
java
Copy
import java.sql.*;
public class JDBCTransac on {
public sta c void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connec on con = DriverManager.getConnec on(
"jdbc:mysql://localhost:3306/mydb", "root", "password");
// Insert data
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO students (name, age) VALUES ('Amit', 20)");
// Read data
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
while (rs.next()) {
System.out.println("Name: " + rs.getString("name") + ", Age: " + rs.getInt("age"));
con.close();
} catch (Excep on e) {
System.out.println("Error: " + e);
o Output: Name: Amit, Age: 20
3. An Overview of RMI Applica ons
What is RMI?
o RMI (Remote Method Invoca on) lets Java programs call methods on another
computer over a network.
o Example: It’s like calling a friend on another computer to do a task for you.
How It Works:
o One program (client) asks another program (server) to do something.
Example: A client asks a server to add two numbers.
o You need an interface, a server, and a client (we’ll skip the full code for
simplicity).
4. Remote Classes and Interfaces
What Are These?
o Remote Interface: Defines methods that can be called remotely (extends
Remote).
o Remote Class: Implements the interface and does the work.
Example:
o Interface: AddInterface with a method add(int a, int b).
o Class: AddImpl implements AddInterface.
5. RMI Architecture
What is RMI Architecture?
o It’s how RMI works:
Client: Calls the remote method.
Server: Runs the method.
Registry: A list that helps the client find the server.
o Example: The client looks up the server in the registry and asks it to add
numbers.
6. RMI Object Hierarchy
What is This?
o It’s the family tree of RMI classes:
Remote (interface): Parent for remote objects.
UnicastRemoteObject: A class for crea ng remote objects.
o Example: Your remote class extends UnicastRemoteObject.
7. Security
What is RMI Security?
o RMI needs security to stop bad users from accessing the server.
o You use a security policy file to set permissions.
o Example: A policy file says, “Only allow trusted users to call methods.”
8. Java Servlets
What Are Servlets?
o Servlets are Java programs that run on a web server to handle web requests.
o Example: When you submit a form on a website, a servlet processes it.
Example (Simple Servlet):
java
Copy
import java.io.*;
import javax.servlet.*;
import javax.servlet.h p.*;
public class MyServlet extends H pServlet {
protected void doGet(H pServletRequest req, H pServletResponse resp) throws
ServletExcep on, IOExcep on {
PrintWriter out = resp.getWriter();
out.println("Hello from Servlet!");
o Output: Shows “Hello from Servlet!” on the webpage.
9. Servlet Life Cycle
Steps:
1. Init: Servlet starts (like se ng up).
2. Service: Servlet handles requests (like doGet or doPost).
3. Destroy: Servlet shuts down.
Example: A servlet starts, serves a webpage, and stops when the server closes.
10. Get and Post Methods
Get:
o Used to get data from the server (visible in the URL).
o Example: Searching “Java” on a website.
Post:
o Used to send data to the server (not visible in the URL).
o Example: Submi ng a login form.
Example (Post):
java
Copy
import java.io.*;
import javax.servlet.*;
import javax.servlet.h p.*;
public class PostServlet extends H pServlet {
protected void doPost(H pServletRequest req, H pServletResponse resp) throws
ServletExcep on, IOExcep on {
String name = req.getParameter("name");
PrintWriter out = resp.getWriter();
out.println("Hello, " + name + "!");
o HTML Form:
html
Copy
<form method="post" ac on="PostServlet">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
o Output: If you type “Amit”, it shows Hello, Amit!.
11. Session Handling
What is Session Handling?
o It’s how a servlet remembers a user across mul ple pages.
o Example: When you log in to a website, it remembers you.
How to Do It?
o Use H pSession to store user data.
Example:
java
Copy
import java.io.*;
import javax.servlet.*;
import javax.servlet.h p.*;
public class SessionServlet extends H pServlet {
protected void doGet(H pServletRequest req, H pServletResponse resp) throws
ServletExcep on, IOExcep on {
H pSession session = req.getSession();
session.setA ribute("username", "Amit");
PrintWriter out = resp.getWriter();
out.println("Session set for: " + session.getA ribute("username"));
o Output: Session set for: Amit
12. Java Beans
What Are Java Beans?
o These are special Java classes that store data and follow rules (like having get
and set methods).
o Example: A Student bean to store name and age.
Example:
java
Copy
public class StudentBean {
private String name;
private int age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
o Servlet Using Bean:
java
Copy
import java.io.*;
import javax.servlet.*;
import javax.servlet.h p.*;
public class BeanServlet extends H pServlet {
protected void doGet(H pServletRequest req, H pServletResponse resp) throws
ServletExcep on, IOExcep on {
StudentBean student = new StudentBean();
student.setName("Amit");
student.setAge(20);
PrintWriter out = resp.getWriter();
out.println("Student: " + student.getName() + ", Age: " + student.getAge());
o Output: Student: Amit, Age: 20
Summary for Your Exam
GUI Design:
o Applets run in browsers, use methods like init(), and need HTML.
o Containers (Frame, Panel) hold components.
o Layouts (Border, Flow, Grid) arrange components.
o AWT and Swing provide components (bu ons, labels).
o Events handle user ac ons (clicks, typing).
Java Database Connec vity (JDBC):
o JDBC connects Java to databases.
o Use Connec on to connect, Statement to run queries.
o RMI lets programs talk over a network.
o Servlets handle web requests (doGet, doPost).
o Java Beans store data with get and set methods.