0% found this document useful (0 votes)
9 views16 pages

Java Swing Overview and Key Concepts

The document provides an overview of Java Swing, a GUI toolkit for Java, detailing its components, features, and class hierarchy. It compares AWT and Swing, explains various GUI components like JLabel, JTextField, JButton, JCheckBox, and JComboBox, and includes example code for creating simple applications. Additionally, it discusses layout managers and their advantages in organizing GUI components.

Uploaded by

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

Java Swing Overview and Key Concepts

The document provides an overview of Java Swing, a GUI toolkit for Java, detailing its components, features, and class hierarchy. It compares AWT and Swing, explains various GUI components like JLabel, JTextField, JButton, JCheckBox, and JComboBox, and includes example code for creating simple applications. Additionally, it discusses layout managers and their advantages in organizing GUI components.

Uploaded by

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

Advance Java Programming (4351603) - Assignment 1 Solution

UNIT-1 JAVA SWING

1. Define Swing.

Answer: Java Swing is a graphical user interface (GUI) toolkit for Java. It is part
of the Java Foundation Classes (JFC) and provides a rich set of widgets and
components for creating desktop applications. Unlike its predecessor, the Abstract
Window Toolkit (AWT), Swing components are "lightweight," meaning they are written
entirely in Java and do not depend on the native operating system's GUI toolkit.
This allows Swing applications to have a pluggable look and feel, making their
appearance consistent across different platforms.

2. Define the following: i. Component, ii. Container, iii. Window, iv. Panel.

Answer: i. Component: In Java's GUI programming, a Component is the abstract base


class for most of the visual elements. It represents any object that has a
graphical representation and can be displayed on the screen and interact with the
user. Examples include buttons, text fields, and labels.
ii. Container: A Container is a special type of component that can hold and manage
other components. It is responsible for arranging the components it contains,
typically using a layout manager. The primary role of a container is to group
components together into a functional unit.
iii. Window: A Window is a top-level container with no borders or menubar. It is a
basic, blank rectangular area on the screen. Objects of the Window class are rarely
used directly. Its subclasses, JFrame and JDialog, are more commonly used to
provide a standard windowing interface for applications.
iv. Panel: A Panel (represented by JPanel in Swing) is a generic, lightweight
container used to group and organize other components. It does not have a title
bar, menu bar, or border by default. Panels are essential for organizing complex
user interfaces by breaking them down into smaller, manageable sections. They can
be placed inside other containers, including other panels or top-level windows like
JFrame.

3. Write the difference between AWT and Swing.

Answer:
Feature AWT (Abstract Window Toolkit) Swing
Component Type AWT components are heavyweight. They rely on the native operating
system's (OS) GUI toolkit to be drawn. Swing components are lightweight. They
are written entirely in Java and do not depend on native OS peers.
Platform Dependency Appearance is dependent on the underlying OS, leading to a
platform-specific look and feel. Offers a pluggable look and feel. The
appearance is consistent across all platforms or can be set to mimic the native OS.
Component Set Provides a basic set of components like Button, TextField, Label,
etc. Provides a much richer and more advanced set of components like tables,
trees, sliders, progress bars, etc. (e.g., JButton, JTextField).
Package Components are in the [Link] package. Components are in the
[Link] package.
Performance Can be faster for some operations as it uses native components. Can be
slower initially but is more flexible and powerful.
Features Lacks advanced features like tooltips, icons on buttons, and extensive
customization. Supports advanced features like tooltips, icons, double buffering
(by default), and extensive customization.
Extensibility Harder to extend and create custom components. Easier to create
custom components by extending existing ones.
4. Explain features of JFC in brief.

Answer: JFC (Java Foundation Classes) is a comprehensive set of GUI components and
services that simplify the development of desktop applications in Java. It
encompasses several key technologies, with Swing being the most prominent.
The main features of JFC are:
1. Swing GUI Components: This is the core of JFC. It provides a rich set
of lightweight, highly customizable GUI components, including buttons, lists,
tables, trees, and more.
2. Pluggable Look and Feel (PLAF): This feature allows the appearance of a
Swing application to be changed at runtime. Applications can use a standard cross-
platform look and feel (like Metal), the native look and feel of the host operating
system, or a custom one.
3. Accessibility API: This API enables assistive technologies, such as
screen readers and magnifiers, to interact with JFC components, making applications
accessible to users with disabilities.
4. Java 2D API: This API provides advanced two-dimensional graphics
capabilities, including sophisticated line art, text rendering, image manipulation,
and geometric transformations. Swing uses this API to render its components.
5. Drag and Drop Support: JFC includes a data transfer framework that
allows developers to implement drag-and-drop functionality both within a Java
application and between a Java application and a native application.

5. Draw Swing class hierarchy.

Answer: Here is a simplified representation of the Swing class hierarchy, showing


the inheritance relationship between key classes.
Object
|
+-- Component (from [Link])
|
+-- Container (from [Link])
|
+-- Window (from [Link])
| |
| +-- Frame (from [Link])
| | |
| | +-- JFrame (from [Link])
| |
| +-- Dialog (from [Link])
| |
| +-- JDialog (from [Link])
|
+-- Panel (from [Link])
| |
| +-- Applet (from [Link])
| |
| +-- JApplet (from [Link])
|
+-- JComponent (from [Link])
|
+-- AbstractButton
| |
| +-- JButton
| +-- JToggleButton
| | |
| | +-- JCheckBox
| | +-- JRadioButton
| |
| +-- JMenuItem
| |
| +-- JMenu
|
+-- JLabel
+-- JList
+-- JComboBox
+-- JPanel
+-- JMenuBar
+-- JPopupMenu
+-- JScrollPane
+-- JSlider
+-- JTable
+-- JTree
+-- JTextComponent
|
+-- JTextField
+-- JTextArea
+-- JPasswordField

6. List and describe commonly used methods of component class.

Answer: The [Link] class is the superclass of all non-menu GUI


components. Here are some of its commonly used methods:
• void setVisible(boolean b): Shows or hides the component. If b is true,
the component is made visible; if false, it is hidden.
• void setSize(int width, int height): Sets the size of the component to
the specified width and height in pixels.
• void setLocation(int x, int y): Moves the component to a new location.
The x and y coordinates are relative to the parent container's coordinate system.
• void setBounds(int x, int y, int width, int height): A convenience
method that sets both the location and size of the component.
• Dimension getSize(): Returns the current size of the component as a
Dimension object.
• Point getLocation(): Returns the current location of the component as a
Point object.
• void setEnabled(boolean b): Enables or disables the component. A
disabled component cannot receive user input.
• boolean isEnabled(): Checks if the component is enabled.
• void add(Component comp): Adds another component to this one (if it's a
container).
• void remove(Component comp): Removes a component from this container.
• void setFont(Font f): Sets the font used to render text on this
component.
• void setBackground(Color c): Sets the background color of the
component.
• void setForeground(Color c): Sets the foreground color (e.g., text
color) of the component.
• void repaint(): Schedules a repaint of the component. The system will
call the paint() method as soon as possible.
7. Explain JApplet and JFrame with example.

Answer: JApplet: JApplet is a Swing class used to create Java applets that can be
embedded in a web page. It is a top-level container that extends
[Link]. Like JFrame, it has a content pane where components are added.
Note:Applets are a deprecated technology and are no longer supported by modern web
browsers.
JFrame: JFrame is the most common top-level container used to create a standard,
windowed desktop application. It has a title bar, borders, and buttons for
minimizing, maximizing, and closing the window. Components are not added directly
to a JFrame but to its content pane, which can be accessed via the getContentPane()
method.
Example (JFrame):
Java

import [Link];
import [Link];
import [Link];

public class JFrameExample {


public static void main(String[] args) {
// Run the GUI code on the Event Dispatch Thread (EDT)
[Link](new Runnable() {
public void run() {
// 1. Create the frame.
JFrame frame = new JFrame("My First JFrame");

// 2. Set what happens when the frame closes.


[Link](JFrame.EXIT_ON_CLOSE);

// 3. Create components and add them to the frame's content pane.


JLabel label = new JLabel("Hello, World!");
[Link]().add(label);

// 4. Set the size of the frame.


[Link](300, 200);

// 5. Make the frame visible.


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

8. Explain JLabel and JTextField with example.

Answer: JLabel: A JLabel is a simple component used to display a non-editable line


of text and/or an image. It is typically used to provide information or labels for
other components.
JTextField: A JTextField is a lightweight component that allows the user to enter
and edit a single line of text. It is useful for getting short text inputs from the
user, such as names, passwords, or search queries.
Example:
Java

import [Link].*;
import [Link];
public class LabelAndTextFieldExample {
public static void main(String[] args) {
[Link](() -> {
JFrame frame = new JFrame("JLabel & JTextField");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300, 100);
[Link](new FlowLayout());

// Create a JLabel
JLabel nameLabel = new JLabel("Enter your name:");

// Create a JTextField with a default width of 15 columns


JTextField nameTextField = new JTextField(15);

// Add components to the frame


[Link](nameLabel);
[Link](nameTextField);

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

9. Explain JTextArea and JButton with example.

Answer: JTextArea: A JTextArea is a component that allows the user to enter and
edit multiple lines of text. It is ideal for displaying or editing larger amounts
of text. It supports features like word wrap and can be placed inside a JScrollPane
to allow scrolling if the text exceeds the visible area.
JButton: A JButton is a standard clickable button. When the user clicks it, it
fires an ActionEvent. An ActionListeneris typically registered with the button to
perform an action when it is clicked. Buttons can display text and/or an icon.
Example:
Java

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

public class TextAreaAndButtonExample {


public static void main(String[] args) {
[Link](() -> {
JFrame frame = new JFrame("JTextArea & JButton");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](350, 200);
[Link](new FlowLayout());

// Create a JTextArea with 5 rows and 20 columns


JTextArea textArea = new JTextArea(5, 20);

// Add the text area to a scroll pane


JScrollPane scrollPane = new JScrollPane(textArea);

// Create a JButton
JButton submitButton = new JButton("Submit");
// Add an ActionListener to the button
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = [Link]();
[Link](frame, "You entered: \n" + text);
}
});

// Add components to the frame


[Link](scrollPane);
[Link](submitButton);

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

10. Explain JCheckBox and JRadioButton with example.

Answer: JCheckBox: A JCheckBox is a component that represents an item that can be


selected or deselected. It appears as a small box that can contain a checkmark.
Checkboxes are used when the user can select multiple options from a set (e.g.,
selecting multiple hobbies).
JRadioButton: A JRadioButton is similar to a checkbox but is typically used in a
group where only one option can be selected at a time (mutually exclusive choices).
To achieve this mutual exclusion, radio buttons must be added to a ButtonGroup
object.
Example:
Java

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

public class CheckBoxAndRadioExample {


public static void main(String[] args) {
[Link](() -> {
JFrame frame = new JFrame("JCheckBox & JRadioButton");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300, 150);
[Link](new FlowLayout());

// JCheckBox example
JCheckBox javaCheckBox = new JCheckBox("Java");
JCheckBox pythonCheckBox = new JCheckBox("Python");

// JRadioButton example
JRadioButton maleRadio = new JRadioButton("Male");
JRadioButton femaleRadio = new JRadioButton("Female");

// Group the radio buttons


ButtonGroup genderGroup = new ButtonGroup();
[Link](maleRadio);
[Link](femaleRadio);
[Link](true); // Set a default selection

// Add components to the frame


[Link](new JLabel("Languages:"));
[Link](javaCheckBox);
[Link](pythonCheckBox);
[Link](new JLabel("Gender:"));
[Link](maleRadio);
[Link](femaleRadio);

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

11. Explain JComboBox and JMenu with example.

Answer: JComboBox: A JComboBox is a component that presents a drop-down list of


items from which the user can select one. It is a more compact alternative to a
list or radio buttons when there are many choices.
JMenu: A JMenu is a component of a menu bar (JMenuBar). It represents a top-level
menu (like "File", "Edit") that, when clicked, displays a drop-down list of menu
items (JMenuItem). Menus are a standard way to organize commands in a GUI
application.
Example:
Java

import [Link].*;

public class ComboBoxAndMenuExample {


public static void main(String[] args) {
[Link](() -> {
JFrame frame = new JFrame("JComboBox & JMenu");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](400, 300);

// --- JMenu Example ---


JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem exitItem = new JMenuItem("Exit");

[Link](e -> [Link](0)); // Exit on click

[Link](openItem);
[Link](exitItem);
[Link](fileMenu);
[Link](menuBar);

// --- JComboBox Example ---


String[] countries = {"India", "USA", "UK", "Canada", "Australia"};
JComboBox<String> countryComboBox = new JComboBox<>(countries);
[Link](50, 50, 100, 30); // Position manually

[Link](null); // Using null layout for simplicity


[Link](countryComboBox);

[Link](true);
});
}
}
12. List types of Layout Managers. What are the advantages of Layout managers?

Answer: Types of Layout Managers: Common layout managers in Swing include:


1. FlowLayout: Arranges components in a left-to-right, top-to-bottom flow,
much like words on a page.
2. BorderLayout: Divides the container into five regions: NORTH, SOUTH,
EAST, WEST, and CENTER.
3. GridLayout: Arranges components in a rectangular grid of equally sized
cells.
4. CardLayout: Stacks components like a deck of cards, allowing only one
to be visible at a time.
5. GridBagLayout: A sophisticated and flexible layout manager that aligns
components vertically and horizontally in a grid of cells, without requiring them
to be of the same size.
6. BoxLayout: Arranges components in a single row (horizontally) or a
single column (vertically).
7. GroupLayout: A flexible layout manager developed for GUI builders,
which works by treating components separately along the horizontal and vertical
axes.
8. SpringLayout: A flexible layout manager that defines relationships
(springs and struts) between the edges of components.
Advantages of Layout Managers:
• Platform Independence: They automatically adjust component sizes and
positions to account for differences in fonts, screen resolutions, and native
component appearances across different operating systems. This makes GUIs robust
and portable.
• Dynamic Resizing: When a window is resized, the layout manager
automatically recalculates the position and size of all components to fit the new
dimensions gracefully. Without a layout manager, components would remain fixed,
leading to a poor user experience.
• Maintainability: They separate the layout logic from the application
logic. This makes the code easier to read, understand, and maintain. Changing the
layout doesn't require rewriting the component creation code.
• Ease of Use: For many standard layouts, they provide a simple and
effective way to arrange components without needing to manually calculate pixel
coordinates.

13. Explain FlowLayout and BorderLayout with example.

Answer: FlowLayout: FlowLayout is the simplest layout manager. It arranges


components in a directional flow, much like lines of text in a paragraph.
Components are added one after another in a row. When a row is full, a new row is
started. The default alignment is centered.
BorderLayout: BorderLayout divides the container into five conceptual regions:
North, South, East, West, and Center. Each region can hold only one component. The
components in the North and South regions extend horizontally to fill the width,
while East and West components extend vertically. The Center component fills the
remaining space.
Example:
Java

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

public class LayoutsExample1 {


public static void main(String[] args) {
[Link](() -> {
// --- BorderLayout Example ---
JFrame borderFrame = new JFrame("BorderLayout");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](400, 300);
[Link](new BorderLayout(5, 5)); // 5px gaps

[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](true);

// --- FlowLayout Example ---


JFrame flowFrame = new JFrame("FlowLayout");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300, 150);
[Link](new FlowLayout([Link])); // Align left

[Link](new JButton("Button 1"));


[Link](new JButton("Button 2"));
[Link](new JButton("Long-Named Button 3"));
[Link](new JButton("Button 4"));
[Link](new JButton("5"));
[Link](true);
});
}
}

14. Explain CardLayout and BoxLayout with example.

Answer: CardLayout: CardLayout treats each component in a container as a "card."


Only one card is visible at a time, and the container acts like a stack of cards.
It is useful for creating wizards or tabbed-pane-like interfaces where the user
navigates between different views within the same window area.
BoxLayout: BoxLayout arranges components either horizontally in a single row or
vertically in a single column. Unlike FlowLayout, BoxLayout does not wrap
components to the next line. It respects the components' maximum, minimum, and
preferred sizes.
Example:
Java

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

public class LayoutsExample2 {


public static void main(String[] args) {
[Link](() -> {
// --- CardLayout Example ---
JFrame cardFrame = new JFrame("CardLayout");
JPanel cardPanel = new JPanel();
CardLayout cardLayout = new CardLayout();
[Link](cardLayout);

[Link](new JLabel("This is Card 1"), "Card1");


[Link](new JLabel("This is Card 2"), "Card2");
JButton nextButton = new JButton("Next Card");
[Link](e -> [Link](cardPanel));

[Link](new BorderLayout());
[Link](cardPanel, [Link]);
[Link](nextButton, [Link]);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);

// --- BoxLayout Example ---


JFrame boxFrame = new JFrame("BoxLayout");
JPanel boxPanel = new JPanel();
// Use Y_AXIS for vertical alignment
[Link](new BoxLayout(boxPanel, BoxLayout.Y_AXIS));

[Link](new JButton("Button 1"));


[Link]([Link](10)); // 10px vertical space
[Link](new JButton("Button 2"));
[Link](new JButton("Button 3"));

[Link](boxPanel);
[Link](200, 250);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
});
}
}

15. Explain GridLayout and GridBagLayout with example.

Answer: GridLayout: GridLayout arranges components in a rectangular grid where all


cells have the exact same size. When you add components, they are placed left-to-
right, top-to-bottom, filling each cell in the grid.
GridBagLayout: GridBagLayout is one of the most flexible and complex layout
managers. It also places components in a grid, but it allows components to span
multiple rows or columns, and cells can have different sizes. The size and position
of each component are controlled by a GridBagConstraints object.
Example:
Java

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

public class LayoutsExample3 {


public static void main(String[] args) {
[Link](() -> {
// --- GridLayout Example ---
JFrame gridFrame = new JFrame("GridLayout");
[Link](new GridLayout(3, 2, 5, 5)); // 3 rows, 2 cols, 5px
gaps

for (int i = 1; i <= 6; i++) {


[Link](new JButton("Button " + i));
}

[Link]();
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);

// --- GridBagLayout Example ---


JFrame gridBagFrame = new JFrame("GridBagLayout");
[Link](new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();

// Button 1
[Link] = 0;
[Link] = 0;
[Link] = [Link];
[Link](new JButton("Button 1"), gbc);

// Button 2
[Link] = 1;
[Link] = 0;
[Link](new JButton("Button 2"), gbc);

// Button 3 (spans 2 columns)


[Link] = 0;
[Link] = 1;
[Link] = 2; // Span 2 columns
[Link] = 20; // Add padding
[Link](new JButton("Button 3 (Spans 2 columns)"), gbc);

[Link]();
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
});
}
}

16. Explain GroupLayout and SpringLayout with example.

Answer: GroupLayout: GroupLayout was developed for use by GUI builder tools (like
NetBeans' Matisse). It works by defining the layout separately for the horizontal
and vertical axes. For each dimension, you group components sequentially or in
parallel. It is very powerful but can be verbose to code manually.
SpringLayout: SpringLayout is a flexible layout manager that allows you to specify
the relationships between the edges of components using Spring objects. Each
"spring" has a minimum, preferred, and maximum value, defining how it stretches or
shrinks. This provides very fine-grained control over layout but can be complex to
manage.
Example (GroupLayout):
Java

import [Link].*;

public class GroupLayoutExample {


public static void main(String[] args) {
JFrame frame = new JFrame("GroupLayout Example");
[Link](JFrame.EXIT_ON_CLOSE);
Container contentPane = [Link]();
GroupLayout groupLayout = new GroupLayout(contentPane);
[Link](groupLayout);

// Auto-create gaps between components


[Link](true);
[Link](true);

JLabel label = new JLabel("Label:");


JTextField textField = new JTextField();
JButton button = new JButton("Button");

// Horizontal Layout
[Link](
[Link]()
.addComponent(label)
.addGroup([Link]([Link]
DING)
.addComponent(textField)
.addComponent(button))
);

// Vertical Layout
[Link](
[Link]()
.addGroup([Link]([Link]
ELINE)
.addComponent(label)
.addComponent(textField))
.addComponent(button)
);

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

17. Define Event, Event Source and Event Listener.

Answer:
• Event: An event is an object that represents a change in state or an
action performed by the user on a GUI component. Examples include clicking a
button, moving the mouse, pressing a key, or closing a window. In Java, events are
represented by classes that inherit from [Link].
• Event Source: An event source is the GUI component that generates an
event. For example, when a user clicks a button, the JButton object is the source
of the ActionEvent. Any object capable of generating an event is an event source.
• Event Listener: An event listener is an object that is notified when an
event occurs. It "listens" for events from a specific source. To be a listener, an
object must implement a specific listener interface (e.g., ActionListener,
MouseListener). The listener contains methods that are executed in response to the
event. The source and listener are connected when the listener is registered with
the source (e.g., [Link](myListener)).

18. List and explain Event classes.

Answer: Event classes in [Link] encapsulate information about a specific


user action.
• ActionEvent: Represents a component-specific action, such as a button
click, a menu item selection, or pressing Enter in a text field. It indicates that
a meaningful action has occurred.
• MouseEvent: Represents an event related to mouse activity, such as
pressing or releasing a mouse button, moving the mouse, or dragging it. It contains
information like the X/Y coordinates of the mouse pointer.
• KeyEvent: Represents a keystroke on the keyboard. It is generated when
a key is pressed, released, or typed. It contains information about which key was
pressed, including virtual key codes and any modifier keys (Shift, Ctrl).
• WindowEvent: Represents an event related to a Window object, such as
opening, closing, activating, deactivating, or iconifying the window.
• ItemEvent: Represents a change in state for a component, such as
selecting or deselecting an item in a JCheckBox, JRadioButton, or JComboBox.
• FocusEvent: Represents the event of a component gaining or losing the
keyboard focus.
• ComponentEvent: A low-level event that indicates a component has moved,
been resized, or changed its visibility.
• AdjustmentEvent: Fired by components like scrollbars (JScrollBar) when
their value changes.

19. List Event Listener interfaces.

Answer: Event Listener interfaces define the methods that a listener object must
implement to process a specific category of events.
• ActionListener (for ActionEvent)
• MouseListener (for mouse button clicks)
• MouseMotionListener (for mouse movement and dragging)
• KeyListener (for keyboard events)
• WindowListener (for window state changes)
• ItemListener (for item selection changes)
• FocusListener (for focus changes)
• ComponentListener (for component resizing, moving, etc.)
• AdjustmentListener (for scrollbar adjustments)

20. Describe MouseEvent and MouseListener interface with example.

Answer: A MouseEvent is generated when the user interacts with a component using
the mouse (e.g., clicking, entering, or exiting the component's area).
The MouseListener interface is used to handle these events. It has five methods:
• mousePressed(MouseEvent e): Invoked when a mouse button has been
pressed on a component.
• mouseReleased(MouseEvent e): Invoked when a mouse button has been
released on a component.
• mouseClicked(MouseEvent e): Invoked when the mouse button has been
clicked (pressed and released).
• mouseEntered(MouseEvent e): Invoked when the mouse pointer enters the
component's area.
• mouseExited(MouseEvent e): Invoked when the mouse pointer exits the
component's area.
Example:
Java

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

public class MouseListenerExample {


public static void main(String[] args) {
[Link](() -> {
JFrame frame = new JFrame("MouseListener Example");
JLabel label = new JLabel("Move mouse over me or click me!",
[Link]);

[Link](new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked at (" + [Link]() + ", " + [Link]()
+ ")");
}
@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed!");
}
@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released!");
}
@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered!");
}
@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited!");
}
});

[Link](label);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
});
}
}

21. Describe KeyEvent and KeyListener interface with example.

Answer: A KeyEvent is generated when the user interacts with a component using the
keyboard, specifically by pressing or releasing a key.
The KeyListener interface is used to handle these events. It has three methods:
• keyPressed(KeyEvent e): Invoked when a key has been pressed down.
• keyReleased(KeyEvent e): Invoked when a key has been released.
• keyTyped(KeyEvent e): Invoked when a character-generating key is
pressed and released. This is not fired for action keys like F1, Shift, etc.
Example:
Java

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

public class KeyListenerExample {


public static void main(String[] args) {
[Link](() -> {
JFrame frame = new JFrame("KeyListener Example");
JTextField textField = new JTextField(20);
JLabel label = new JLabel("Type in the text field above.");

[Link](new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
// Not commonly used for game-like input
}
@Override
public void keyPressed(KeyEvent e) {
[Link]("Key Pressed: " +
[Link]([Link]()));
}
@Override
public void keyReleased(KeyEvent e) {
[Link]("Key Released: " +
[Link]([Link]()));
}
});

[Link](new [Link]());
[Link](textField);
[Link](label);
[Link](400, 100);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
});
}
}

22. Explain WindowListener interface with example.

Answer: The WindowListener interface is used for receiving WindowEvents. An object


that implements this interface can be registered with a Window (or its subclasses
like JFrame) to be notified of changes in the window's state, such as opening,
closing, activation, etc.
It has seven methods:
• windowOpened(WindowEvent e): Invoked the first time a window is made
visible.
• windowClosing(WindowEvent e): Invoked when the user attempts to close
the window from the window's system menu.
• windowClosed(WindowEvent e): Invoked after a window has been closed as
the result of calling dispose.
• windowIconified(WindowEvent e): Invoked when the window is changed from
a normal to a minimized state.
• windowDeiconified(WindowEvent e): Invoked when a window is changed from
a minimized to a normal state.
• windowActivated(WindowEvent e): Invoked when the Window is set to be
the active Window.
• windowDeactivated(WindowEvent e): Invoked when a Window is no longer
the active Window.
Because implementing all seven methods can be cumbersome, the WindowAdapter class
is often used. It provides empty implementations of all methods, allowing you to
override only the ones you need.
Example (using WindowAdapter):
Java

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

public class WindowListenerExample {


public static void main(String[] args) {
[Link](() -> {
JFrame frame = new JFrame("WindowListener Example");
JLabel label = new JLabel("Try to close this window.",
[Link]);

// Using WindowAdapter for convenience


[Link](new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int choice = [Link](frame,
"Are you sure you want to close this window?",
"Confirm Close",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (choice == JOptionPane.YES_OPTION) {
[Link](JFrame.EXIT_ON_CLOSE);
} else {
// Prevent closing
[Link](JFrame.DO_NOTHING_ON_CLOSE);
}
}

@Override
public void windowOpened(WindowEvent e) {
[Link]("Window Opened!");
}
});

[Link](label);
[Link](400, 200);
// Default close operation is handled by our listener now
[Link](JFrame.DO_NOTHING_ON_CLOSE);
[Link](true);
});
}
}

Google Privacy PolicyOpens in a new windowGoogle Terms of ServiceOpens in a new


windowYour privacy and Gemini AppsOpens in a new window
Gemini may display inaccurate info, including about people, so double-check its
responses.
Go to Gemini

Google Account
Prasen
prasen3110@[Link]

You might also like