Module 4 Java
Module 4 Java
Santosh )
● Applet Life Cycle
● Running Applets
● Graphics Class
○ Color Class
○ Font Class
● Limitations of Applets
● Layout Management
○ FlowLayout
○ BorderLayout
○ GridLayout
○ Event Classes
● Introduction to Swing
start() After init() and when applet restarts Start animations or actions
paint() Whenever applet needs to redraw itself Draw graphics or text on screen
Example:
import java.applet.Applet;
import java.awt.Graphics;
2. Running Applets
● Traditionally, applets run inside a web browser using an HTML <applet> tag.
● Since browsers don’t support Java applets anymore, we use appletviewer, a tool that
comes with JDK, to run applets.
HTML Example:
<applet code="SimpleApplet.class" width="300" height="100"></applet>
4. Graphics Class
This class helps you draw shapes, images, and text on screen inside paint() method.
Important Methods:
● drawLine(int x1, int y1, int x2, int y2): Draw a line between two points.
● drawOval(int x, int y, int width, int height): Draw an oval inside the
specified rectangle.
Example:
public void paint(Graphics g) {
g.setColor(Color.BLUE);
g.drawString("Welcome!", 50, 50);
g.drawRect(40, 60, 100, 50);
g.fillOval(40, 120, 100, 50);
}
5. Color Class
Represents colors in RGB format (Red, Green, Blue), values 0 to 255.
● You can use predefined colors: Color.RED, Color.GREEN, Color.BLUE, etc.
6. Font Class
Used to specify the font style when drawing text.
g.setFont(font);
g.drawString("Bold Text", 50, 100);
7. Limitations of Applets
● Security Restrictions: Cannot read/write files on user’s computer or connect to
arbitrary network locations (only the server they came from).
Because of these limitations, applets are mostly obsolete now and replaced by technologies like
Java Web Start or web frameworks.
8. Interfaces of Java AWT
Java AWT provides many interfaces that components implement to handle user events:
9. Layout Management
Layout managers control how components (buttons, text fields) are arranged inside containers
(Frames, Panels).
9.1 FlowLayout
setLayout(new FlowLayout(FlowLayout.LEFT));
9.2 BorderLayout
● Divides container into 5 regions: North, South, East, West, Center.
setLayout(new BorderLayout());
add(button1, BorderLayout.NORTH);
add(button2, BorderLayout.CENTER);
9.3 GridLayout
● The event is delivered to one or more listener objects registered to handle the event.
This model improves efficiency by separating event generation and handling, and lets multiple
listeners react to the same event.
import javax.swing.*;
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
import javax.swing.*;
import java.awt.event.*;
frame.add(label);
frame.add(textField);
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}