0% found this document useful (0 votes)
3 views

Java Module 5

Module 5 covers GUI programming in Java, focusing on applets, event handling, and Swing controls. It explains the applet lifecycle, event delegation model, and provides examples of various GUI components like JButton, JLabel, and JTextField. Additionally, it contrasts applets with Swing and suggests project ideas for practicing Swing programming skills.

Uploaded by

saikumarvenkat60
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Module 5

Module 5 covers GUI programming in Java, focusing on applets, event handling, and Swing controls. It explains the applet lifecycle, event delegation model, and provides examples of various GUI components like JButton, JLabel, and JTextField. Additionally, it contrasts applets with Swing and suggests project ideas for practicing Swing programming skills.

Uploaded by

saikumarvenkat60
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Module 5

GUI PROGRAMMING
GUI Programming With Applets: Applets - Applet Class, Applet skeleton, Simple
Applet; Delegation event model - Events, Event sources, Event Listeners, Event
classes, handling mouse and keyboard events.
Exploring Swing Controls: JLabel and Image Icon, JText Field, JButton,
JCheckBox, JRadioButton, JTabbed Pane, JList, JCombo Box.

Applet in Java
An applet is a small Java program that runs inside a web browser or an applet viewer.
It is primarily used for creating dynamic and interactive web applications. Unlike standalone
Java applications, applets require a web environment with support for the Java Plugin or
AppletViewer.
Packages Used in Applet Programming
 The primary package used for creating applets is:
import java.applet.*;// Provides the base class for creating applets
import java.awt.*;// Used for graphical operations like drawing text, shapes, etc.
 For web page integration, we use HTML <applet> tag

Applet Skeleton: (Applet Life Cycle)


An applet follows a well-defined lifecycle managed by the Java Applet API. It
consists of the following methods:

1. init():
o Called once when the applet is initialized.
o Used for setting up resources.
2. start():
o Called when the applet is started or restarted.
o Executes when the web page containing the applet is opened or revisited.
3. paint(Graphics g):
o Used for rendering graphics and displaying content.
o Runs whenever the window needs to be repainted.
4. stop():
o Called when the applet is temporarily stopped (e.g., when navigating away
from the page).
o Can be restarted using start().
5. destroy():
o Called when the applet is closed or removed.
o Used to free up resources.
Example Simple Java Applet:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleApplet extends Applet implements ActionListener {
Label lblNum1, lblNum2, lblTotal;
TextField txtNum1, txtNum2, txtTotal;
Button btnAdd;
public void init() {
setLayout(new GridLayout(4, 2, 10, 10));
lblNum1 = new Label("First Number:");
txtNum1 = new TextField();
lblNum2 = new Label("Second Number:");
txtNum2 = new TextField();
lblTotal = new Label("Result:");
txtTotal = new TextField();
txtTotal.setEditable(false);
btnAdd = new Button("Add");
btnAdd.addActionListener(this);
add(lblNum1);
add(txtNum1);
add(lblNum2);
add(txtNum2);
add(lblTotal);
add(txtTotal);
add(btnAdd);
}
public void actionPerformed(ActionEvent e) {
int num1 = Integer.parseInt(txtNum1.getText());
int num2 = Integer.parseInt(txtNum2.getText());
int sum = num1 + num2;
txtTotal.setText(String.valueOf(sum));
}
}
Execution HTML Code:
<html>
<body>
<applet code="SimpleApplet.class" width="400" height="300"></applet>
</body>
</html>
//Two Mark Questions
Delegation Event Model in Java:
The Delegation Event Model is a mechanism for handling events in Java, where an
event source delegates event handling to an event listener. import java.awt.event.* package
for handling events.

1. What is an Event?
An event in Java is an occurrence, such as a mouse click, key press, or button click,
that triggers an action. Events are objects that store information about the occurrence.
Example of Events:
 Clicking a button (ActionEvent)
 Pressing a key (KeyEvent)
 Moving the mouse (MouseEvent)

2. What is an Event Source?


An event source is the component that generates an event. It is usually a GUI
component such as a button, text field, or window.
Example of Event Sources:
 Button generates ActionEvent when clicked.
 TextField generates TextEvent when text changes.
 Window generates WindowEvent when opened/closed.

3. What is an Event Listener?


An Event Listener is an interface in Java used to handle events like button clicks,
key presses, or mouse actions. It is used to listen for events from a source (like a button)
and respond to those events.
button.addActionListener(this); // Register ActionListener to the button

Example of Event Listeners:


Listener Interface Handles This Event
ActionListener Button clicks, menu actions
KeyListener Keyboard key press, release
MouseListener Mouse click, press, release

4. What are Event Classes?


Event classes are predefined in the java.awt.event package and contain details about
an event.
Common Event Classes:
Event Class Description
ActionEvent Occurs when a button or menu is clicked
KeyEvent Occurs when a key is pressed or released
MouseEvent Occurs on mouse clicks or movement
WindowEvent Occurs when a window is opened/closed

5. Handling Mouse Events


Handling mouse events refers to the process of responding to actions performed with
the mouse, such as clicking, pressing, releasing, entering, or exiting a component in a
graphical user interface (GUI).
Simple Example (Java):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseExample extends JFrame implements MouseListener {
JLabel label;
MouseExample() {
label = new JLabel("Click anywhere");
add(label);
addMouseListener(this);
setSize(300, 200);
setLayout(new FlowLayout());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked!");
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public static void main(String[] args) {
new MouseExample();
}
}

Output: When you click anywhere in the window, the label text changes to "Mouse
Clicked!".

6. Handling Keyboard Events


Handling keyboard events means writing code to respond to keyboard actions like key
press, key release, or key typing in a GUI application using event listeners.
Simple Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyExample extends JFrame implements KeyListener {
JLabel label = new JLabel("Press any key");
KeyExample() {
add(label);
addKeyListener(this);
setSize(250, 150);
setLayout(new FlowLayout());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setFocusable(true);
}
public void keyPressed(KeyEvent e) {
label.setText("Key Pressed: " + e.getKeyChar());
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new KeyExample();
}
}
Exploring Swing Controls
Swing is a part of Java used to create window-based applications. It provides GUI
components like buttons, labels, text fields, and more to build user interfaces.
1. JButton:
Definition: A JLabel is used to display a short string or text message on the GUI.
Use: Common for displaying static text or descriptions.
JButton Example:
import javax.swing.*;
public class JButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JButton Example");
JButton button = new JButton("Click Me");
frame.add(button);
frame.setSize(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:

2. JLabel:
Definition: A JLabel is used to display a short string or text message on the GUI.
Use: Common for displaying static text or descriptions.
JLabel Example:
import javax.swing.*;
public class JLabelExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JLabel Example");
JLabel label = new JLabel("Label Text");
frame.add(label);
frame.setSize(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:

3. JTextField:
Definition: A JTextField allows users to enter a single line of text.
Use: Ideal for entering short inputs like names, numbers, or search queries.
JTextField Example:
import javax.swing.*;
public class JTextFieldExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextField Example");
JTextField textField = new JTextField("Initial Text", 15);
frame.add(textField);
frame.setSize(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:

4. JTextArea:
Definition: A JTextArea is used to enter or display multiple lines of text.
Use: Suitable for writing paragraphs, feedback, or comments.
JTextArea Example:
import javax.swing.*;
public class JTextAreaExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextArea Example");
JTextArea textArea = new JTextArea("Initial Text", 5, 20);
frame.add(new JScrollPane(textArea));
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:

5. JComboBox:
Definition: A JComboBox provides a dropdown list of items to choose from.
Use: Good for selecting one option from a list (e.g., country, gender).
JComboBox Example:
import javax.swing.*;
public class JComboBoxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JComboBox Example");
JComboBox<String> comboBox = new JComboBox<>(new String[]{"Option
1", "Option 2"});
frame.add(comboBox);
frame.setSize(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:

6. JCheckBox:
Definition: A JCheckBox allows the user to select or deselect an option.
Use: Used when multiple selections are allowed (e.g., interests, hobbies).
JCheckBox Example:
import javax.swing.*;
public class JCheckBoxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JCheckBox Example");
JCheckBox checkBox = new JCheckBox("Check me");
frame.add(checkBox);
frame.setSize(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:

7. JRadioButton:
Definition: A JRadioButton lets the user select only one option from a group.
Use: Perfect for choosing one option among many (e.g., gender selection).
JRadioButton Example:
import javax.swing.*;
public class JRadioButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JRadioButton Example");
JRadioButton radioButton = new JRadioButton("Option 1");
frame.add(radioButton);
frame.setSize(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:

8. JList:
Definition: A JList displays a list of items, allowing single or multiple selections.
Use: Used for selecting one or more items from a list (e.g., items to purchase).
JList Example:
import javax.swing.*;
public class JListExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JList Example");
JList<String> list = new JList<>(new String[]{"Item 1", "Item 2"});
frame.add(new JScrollPane(list));
frame.setSize(200, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:

9. JTabbedPane Example:
Definition: A JTabbedPane provides tabs that can switch between different panels or views.
Use: Helpful in organizing content into different sections like in browsers or settings
windows.
JTabbedPane Example:
import javax.swing.*;
public class JTabbedPaneExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTabbedPane Example");
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel1 = new JPanel();
tabbedPane.addTab("Tab 1", panel1);
frame.add(tabbedPane);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:
Difference between Applet and Swing:

Feature Applet Swing


Definition A small Java program that runs A set of Java libraries for building
inside a web browser. desktop GUI applications.
Usage Adds interactive features to web Used to create standalone
pages like games or tools. applications with graphical
interfaces.
Dependency Depends on the browser’s Java Does not rely on browsers; runs
plugin to run (now mostly independently.
unsupported).
Flexibility Less flexible; limited UI More flexible; allows more control
customization. over the appearance and behavior.
Example A simple game embedded in a A desktop calculator application.
webpage.

List of Swing GUI Java application ideas for practicing your Swing programming skills:

1. Calculator
2. To-Do List Application
3. Simple Notepad (Text Editor)
4. Student Management System
5. Basic Login System
6. Tic-Tac-Toe Game
7. Unit Converter (Length, Weight, Temperature)
8. Currency Converter
9. Address Book
10. Simple Chat Application (GUI)
11. Stopwatch
12. Countdown Timer
13. Image Viewer
14. Quiz Application
15. Expense Tracker
16. Game Score Tracker
17. Simple Calendar
18. File Explorer
19. Simple Paint Program
20. Weather App

You might also like