0% found this document useful (0 votes)
6 views17 pages

Java AWT and Swing GUI Components Guide

The document discusses the limitations of AWT in Java, explaining its heavyweight components, lack of pluggable look and feel, and limited GUI controls. It also covers the MVC architecture, mouse and keyboard event handling, and various GUI components like buttons, labels, and text fields. Additionally, it explains layout managers, including BorderLayout and FlowLayout, and provides examples of applets and event handling in Java.

Uploaded by

suneetha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views17 pages

Java AWT and Swing GUI Components Guide

The document discusses the limitations of AWT in Java, explaining its heavyweight components, lack of pluggable look and feel, and limited GUI controls. It also covers the MVC architecture, mouse and keyboard event handling, and various GUI components like buttons, labels, and text fields. Additionally, it explains layout managers, including BorderLayout and FlowLayout, and provides examples of applets and event handling in Java.

Uploaded by

suneetha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1. a. What are the main limitations of AWT in Java?

 AWT components are heavyweight components


 AWT doesn’t support pluggable look and feel
 AWT programs are not portable & using old framework for creating
GUIs
 AWT supports limited number of GUI controls
 More code is needed to implement AWT controls
 AWT doesn’t follow MVC

b. What is MVC architecture in Java?


MVC Architecture (Model–View–Controller)
Model
 Stores the data

 Handles business logic

 Independent of UI

View
 Displaying the data to the user

 Represents the UI components

 Updates when the Model changes

Controller
 Handles user input (clicks, typing, actions)

 Updates the Model

 Coordinates between Model and View

c. Discuss the handling of mouse events in Java with an example


program.
Handling Mouse Events
A mouse event occurs when a user interacts with the mouse over a GUI
component.
for example:
 Clicking a button

 Moving the mouse over a window

 Dragging the mouse


Mouse events can be handled using interfaces MouseListener and
MouseMotionListener.
In EventSource the user must register the MouseListener and
MouseMotionListener.
MouseListener:This interface is used to handle mouse click events.
Methods
 mouseClicked(MouseEvent e): Called when the mouse button is
clicked.
 mousePressed(MouseEvent e): Called when a mouse button is
pressed.
 mouseReleased(MouseEvent e): Called when a mouse button is
released.
 mouseEntered(MouseEvent e): Called when the mouse enters the
component.
 mouseExited(MouseEvent e): Called when the mouse exits the
component.
MouseMotionListener: This interface is used to handle mouse
movement events (mouse moved and dragged).
Methods
mouseMoved(MouseEvent e): Called when the mouse is moved over
the component.
mouseDragged(MouseEvent e): Called when the mouse is dragged (i.e.,
moved while holding down a button).
Methods
getX(): Returns the X-coordinate (horizontal position) of the mouse
pointer when the event occurred.
getY(): Returns the Y-coordinate (vertical position) of the mouse pointer
when the event occurred.
import [Link].*;
[Link].*;
[Link].*;
public class HandleMouseEvent extends JFrame implements
MouseListener,MouseMotionListener {
JLabel l;
Public static void main(String[] args) {
New HandleMouseEvent();
}
HandleMouseEvent() {
setTitle("Mouse Event Example");
setSize(400,400);
l = new JLabel("");
add(l);
addMouseListener(this);
addMouseMotionListener(this);
setVisible(true);
}
Public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");
}
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed"); }
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released"); }
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered"); }
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited"); }
public void mouseDragged(MouseEvent e) {
[Link]("Mouse Dragged to "+ [Link]()+","+[Link]()); }
public voidmouseMoved(MouseEvent e) {
[Link]("Mouse Moved to "+ [Link]()+","+[Link]());
} }

2. a. Define container class?


 A Container is a special type of component that can hold and
organize other components inside it.
 It is used to create the layout and structure of the GUI.
Examples include JFrame, JPanel, and JDialog.
b. List any four components with their uses.
JButton:
The JButton class is used to create a labeled button.
A JButton is a push button that performs a specific action.
JLabel:
The JLabel class is a component for placing text or images in a
container.
It is used to display a single line of text.
JTextField
The JTextField allows the user to enter and edit a single line of text.
JTextArea :
The JTextArea class allows the user to enter multiple lines of text.

c. Explain the user interface components – labels, text fields,


buttons, checkboxes and radio buttons.
Graphical User Interface (GUI) components are used to build interactive
applications. The most used components are labels, text fields, buttons,
checkboxes, and radio buttons.

1. Labels
The JLabel class is a component for placing text or images in a container.
It is mainly used for identifying or describing other components like text
fields or buttons.
Uses:
 To display information or instructions

 To name input fields (e.g., “Name:”, “RollNo:”)

 To show messages or results

Syntax:
JLabel label = new JLabel("Enter Name:");

2. Text Fields
A TextField (JTextField) allows the user to enter and edit a single line of
text. It is one of the most common input components in forms.
Uses:
 Accepting user input such as name, age, phone number

 Displaying editable values

Syntax:
JTextField textField = new JTextField(20);

3. Buttons
The JButton class is used to create a labeled button.
A JButton is a push button that performs a specific action.
Buttons generate ActionEvent and are used to control the flow of the
application.
Uses:
 Submitting data

 Performing calculations

 Navigating between screens

Syntax:
JButton button = new JButton("Submit");

4. Checkboxes
A Checkbox (JCheckBox) is used when the user needs to choose multiple
options independently from a group. Each checkbox works individually.
Uses:
 Selecting hobbies (Music, Sports, Reading)

 Choosing multiple settings or preferences

 Enabling or disabling features

Syntax:
JCheckBox checkBox = new JCheckBox("Music");

5. Radio Buttons
A Radio Button (JRadioButton) allows the user to choose only one option
from a set. To make them mutually exclusive, they must be placed inside
a ButtonGroup.
Uses:
 Gender selection (Male, Female)

 Choosing payment mode (Card, Cash, UPI)

 Selecting difficulty level (Easy, Medium, Hard)


Syntax:
JRadioButton m = new JRadioButton("Male");
JRadioButton fm = new JRadioButton("Female");

ButtonGroup bg = new ButtonGroup();


[Link](m);
[Link](fm);

3. a. What is swing in Java?


 Swing is a GUI (Graphical User Interface) toolkit in Java that
provides a set of graphical components to create desktop
applications with a rich user interface.
 It is a part of the Java Foundation Classes (JFC), which also includes
AWT (Abstract Window Toolkit).

b. List out the differences Between AWT and Swing.


AWT Swing
AWT components are Swing components are lightweight
heavyweight components components
Doesn’t support pluggable look
Supports pluggable look and feel
and feel
Uses [Link] package Uses [Link] package
Provides advanced GUI controls
Provides limited GUI controls
(labels, tables, panes, etc.)
Needs more code to implement Needs less code to implement
functionality functionality
Does not follow MVC
Follows MVC architecture
architecture

c Explain JTree and JTable components in Swing. How are they


used to represent structured and tabular data?
JTree
A JTree is a Swing component used to display hierarchical or structured
data in a tree-like format.
It shows data in parent-child relationships, where each item is called a
node.
JTree Represents Structured Data
 Data is arranged in a hierarchy (like folders and files).

 Each branch can have multiple child nodes.

 Nodes can be expanded or collapsed by the user.

 The root node is at the top, with children arranged below.

Common Uses
 File explorers (like Windows Explorer)

 Project structure in IDEs (like Eclipse, IntelliJ)

 Organization charts

Syntax
JTree tree = new JTree();
add(tree);

import [Link].*;
import [Link];

public class SimpleTree {


public static void main(String[] args) {
JFrame f = new JFrame("JTree Example");
[Link](300, 200);
DefaultMutableTreeNode root = new
DefaultMutableTreeNode("Courses");
DefaultMutableTreeNode c1 = new
DefaultMutableTreeNode("Java");
DefaultMutableTreeNode c2 = new
DefaultMutableTreeNode("Python");

[Link](c1);
[Link](c2);

JTree tree = new JTree(root);


[Link](tree);
[Link](true);
}
}
JTable
A JTable is a component used for displaying tabular data in rows and
columns.
It allows editing, selecting, and customizing data in a grid-like structure.
JTable Represents Tabular Data
 Data is arranged in rows and columns like a spreadsheet.

 Column headers describe the type of data (e.g., Name, Age, Marks).

 Rows represent individual records or entries.

 Supports sorting and editing cells.

Common Uses
 Databases records display

 Student marks table

 Any application that requires structured table data

import [Link].*;
public class SimpleJTable {
public static void main(String[] args) {
JFrame f = new JFrame("Simple JTable");
[Link](400, 200);

String data[][] = {
{"1", "AAA", "DS"},
{"2", "BBB", "CSE"},

};
String col[] = {"Roll No", "Name", "Branch"};

JTable table = new JTable(data, col);


[Link](table);
[Link](true);
}
}

4. a. What is an event? What are the sources of events?


Event: Change in the state of an object is known as an event.
Events are generated because of user interaction (like button click, key
press, mouse movement) with the graphical user interface components.
Sources of Events:
Event sources are GUI components that generate events.
 Button generates ActionEvent
 Checkbox generates ItemEvent
 Mouse generates MouseEvent
 Keyboard generates KeyEvent
 Window generates WindowEvent

b. Write short notes on Delegation Event Model.


The Delegation Event Model is Java’s event-handling mechanism where
an event source delegates the responsibility of handling events to an
external event listener.
The source generates the event, and the listener (which implements a
listener interface) receives and handles it.

c. Explain Keyboard Event Handling in java.


Handling Keyboard Events
A keyboard event occurs when a user interacts with the keyboard.
for example, when a key is pressed, released, or typed inside a GUI
component.
In Swing keyboard events are captured using key listeners.
In EventSource the user must register the KeyListener.

Key Event Types


There are three main key events:
1. keyPressed(KeyEvent e): This is triggered when a key is pressed.
2. keyReleased(KeyEvent e): This is triggered when a key is released.
3. keyTyped(KeyEvent e): This is triggered when a key is typed
(which includes pressing and releasing the key).

import [Link].*;
import [Link].*;
import [Link].*;
public class HandleKeyboardEvent extends JFrame implements
KeyListener {
JLabel l;
public static void main(String[] args) {
new HandleKeyboardEvent();
}
HandleKeyboardEvent() {
setTitle("Key Listener Example");
setSize(400, 200);
l = new JLabel("");
add(l);
addKeyListener(this);
setVisible(true);
}
public void keyTyped(KeyEvent e) {
[Link]("Key Typed: " + [Link]());
}
public void keyPressed(KeyEvent e) {
int keyCode = [Link]();
[Link]("Key Pressed: " + [Link](keyCode));
}
public void keyReleased(KeyEvent e) {
int keyCode = [Link]();
[Link]("Key Released: " + [Link](keyCode));
}}

d. How do you create an Applet in Java? What are the 4 methods


of applet class?
Applet An applet is a small Java program that runs inside a web browser
or an applet viewer.
To create an applet in Java
1. Import the Applet package.
2. Create a class that extends Applet.
3. Override the applet lifecycle methods ( init(), start(), stop(),
destroy()).
4. Use the paint(Graphics g) method to draw output.
5. Run the applet using an HTML file or appletviewer.
Four Methods of Applet Class
1. init()
o Called once when the applet is loaded.

o Used for initialization.

2. start()
o Called after init() or when the applet becomes active.

o Used to start processes or animations.

3. stop()
o Called when the applet becomes inactive.

o Used to pause tasks.

4. destroy()
o Called when the applet is being removed from memory.

o Used to release resources.

import [Link];
import [Link].*;

public class SimpleApplet extends Applet {


public void init() {
setBackground([Link]);
}
public void start() {
[Link]("Applet Started");
}
public void stop() {
[Link]("Applet Stopped");
}
public void destroy() {
[Link]("Applet Destroyed");
}
public void paint(Graphics g) {
[Link]([Link]);
[Link]("Simple Applet Program", 40, 50);
}
}
HTML File to Run the Applet
Save as [Link]:
<html>
<body>
<applet code="[Link]" width="400" height="200">
</applet>
</body>
</html>

5. a. What are the uses of Layout Managers?


Layout Managers are used to
 Automatically arrange components inside a container.

 Adjust component sizes and positions when the window is resized.

 Provide consistent layout across different screen sizes and

platforms.

b. List the layout manager types.


Types of Layout Managers
 BorderLayout
 FlowLayout
 GridLayout
 GridBagLayout
 CardLayout

c. Create a java program to demonstrate Border Layout.


 The BorderLayout is used to arrange the components in five regions:
NORTH, SOUTH, EAST, WEST and CENTER.
 Each region (area) may contain one component only.
 It is the default layout of Jframe.

import [Link].*;
import [Link].*;
public class BorderLayoutEx {
public static void main(String[] args) {
JFrame f = new JFrame("BorderLayout Example");
[Link](new BorderLayout(10,10));
[Link](new JButton("North"), [Link]);
[Link](new JButton("South"), [Link]);
[Link](new JButton("East"), [Link]);
[Link](new JButton("West"), [Link]);
[Link](new JButton("Center"), [Link]);
[Link](400, 300);
[Link](true);
} }

d. Explain the working of FlowLayout with an example.


 The FlowLayout is used to arrange the components in a single row,
from left to right.
 Fields of FlowLayout are LEFT, RIGHT and CENTER.
 It is the default layout manager of JPanel.
 It automatically wraps to a new line when there is no space.
 Components are center aligned by default but can also be left or right
aligned.

Constructors:
1. FlowLayout(): Initializes with center alignment, and default gaps
(5px horizontal and vertical).
2. FlowLayout(int alignment): Allows setting the alignment of
components to either left, center, or right with default gaps.
3. FlowLayout(int alignment, int hgap, int vgap): Allows
customizing the alignment and the horizontal and vertical gaps
between components.

import [Link].*;
import [Link].*;
public class FlowLayoutEx{
public static void main(String[] args) {
JFrame f = new JFrame("FlowLayout Example");
[Link](new FlowLayout([Link],10,10));
[Link](new JLabel("Programming Languages"));
[Link](new JButton("C"));
[Link](new JButton("JAVA"));
[Link](new JButton("PYTHON"));
[Link](new JButton("RUBY"));
[Link](new JButton("C++"));
[Link](400, 200);
[Link](true);
}
}
6. a. Differentiate between JCheckbox and JRadio Button
JCheckBox JRadioButton
Allows only one selection in a
Allows multiple selections
group
Works independently Works as part of a ButtonGroup
Shows a check mark (✔) when Shows a filled dot (●) when
selected selected
Used for yes/no or multi-choice
Used for single-choice options
options

b. What is the need of Adapter class?


 An adapter class is a special class that provides default (empty)
implementations for all methods of a listener interface.
 It allows developers to override only the methods they need, instead
of implementing every method of the interface.

c. Describe in detail the various event listener interfaces.


Event Listeners It is an object that is notified when an event occurs. It
has two major requirements.
 First, it must have been registered with one or more sources to
receive notifications about specific types of events.
 Second, it must implement methods to receive and process these
notifications.

Different types of Event Listeners

The ActionListener Interface:


It defines the actionPerformed( ) method that is invoked when an action
event occurs. void actionPerformed(ActionEvent e)

The ItemListener Interface:


It defines the itemStateChanged( ) method that is invoked when the state
of an item changes. void itemStateChanged(ItemEvent e)
The KeyListener Interface:
This interface defines three methods.
keyPressed( ) , keyReleased( ) methods are invoked when a key is pressed
and released.
The keyTyped( ) method is invoked when a character has been entered.

void keyPressed(KeyEvent e)
void keyReleased(KeyEvent e)
void keyTyped(KeyEvent e)

The MouseListener Interface:


This interface defines five methods.
If the mouse is clicked on a component, mouseClicked( ) is invoked.
When the mouse enters a component, mouseEntered( ) method is called.
When it leaves, mouseExited( ) is called.
The mousePressed( ) and mouseReleased( ) methods are invoked when
the mouse is pressed and released,respectively.
void mouseClicked(MouseEvent e)
void mouseEntered(MouseEvent e)
void mouseExited(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)

The MouseMotionListener Interface:


This interface defines two methods.
The mouseDragged( ) method is called when the mouse is dragged.
ThemouseMoved( ) method is called when the mouse ismoved.
void mouseDragged(MouseEvent e),
void mouseMoved(MouseEvent e)

The WindowListener Interface:


This interface defines seven methods.
ThewindowActivated( ) and windowDeactivated( ) methods are invoked
when a window is activated or deactivated, respectively.
If a window is iconified, the windowIconified( ) method is called.
(Minimized)
When a window is deiconified, the windowDeiconified( ) method is
called.
When a window is opened or closed, the windowOpened( ) or
windowClosed( ) methods are called, respectively.
The windowClosing( ) method is called when a window is being closed.
void windowActivated(WindowEvent e)
void windowClosed(WindowEvent e)
void windowClosing(WindowEvent e)
void windowDeactivated(WindowEvent e)
void windowDeiconified(WindowEvent e)
void windowIconified(WindowEvent e)
void windowOpened(WindowEvent e)

The TextListener Interface:


It defines the textChanged( ) method that is invoked when a change
occurs in a text area or text field. void textChanged(TextEvent e)

d. Describe in detail the various event classes.


Event Classes
ActionEvent: Generated when a button is pressed, a list item is double-
clicked, or a menu item is selected.
ComponentEvent: Generated when a componentis hidden, moved,
resized, or becomes visible.
ContainerEvent: Generated when a componentis added to or removed
from a container.
ItemEvent: Generated when a check box or list item is clicked; also
occurs when a choice selection is made or a checkable menu item is
selected or deselected.
KeyEvent: Generated when input is received from the keyboard.
MouseEvent:Generated when the mouse is dragged, moved, clicked,
pressed, or released; also generated when the mouse enters or exits a
component.
TextEvent: Generated when the value of a text area or text field is
changed.
WindowEvent: Generated when a windowis activated, closed,
deactivated, deiconified, iconified, opened, or quit.

You might also like