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

JAVA Unit 4

The document provides an overview of Java's GUI support through AWT and Swing, detailing their components, layout managers, and event handling. It explains the differences between AWT and Swing, highlighting the limitations of AWT and the enhanced features of Swing. Additionally, it includes code examples for creating GUI applications using Frames and Applets, as well as working with menus and file dialogs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

JAVA Unit 4

The document provides an overview of Java's GUI support through AWT and Swing, detailing their components, layout managers, and event handling. It explains the differences between AWT and Swing, highlighting the limitations of AWT and the enhanced features of Swing. Additionally, it includes code examples for creating GUI applications using Frames and Applets, as well as working with menus and file dialogs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Event handling using

abstract window
toolkit(AWT) and
swing components
V2V RAJAN
CLASSES
SHUKLA
Professor
V2V Classes
Java and GUI support

Java provides robust support for creating Graphical User


Interfaces (GUIs) through Abstract Window Toolkit
(AWT) and Swing libraries.
AWT was the original platform-independent windowing,
graphics, and user-interface toolkit. Swing, built on
AWT, offers a richer set of components with enhanced
features like pluggable look and feel.
AWT Components Class Hierarchy
Creating GUI Applications Using Frame
and Applet

Frame: A top-level container used to create standalone


windows.

Applet: A small application embedded in a web browser,


useful for dynamic content.
Program Using
Frame
import java.awt.*;

public class FrameExample {


public static void main(String[] args) { Frame
frame = new Frame("My Frame");
frame.setSize(300, 200);
frame.setVisible(true);
frame.add(new Label("Welcome to AWT Frame!"));
}
}
Program Using Applet

import java.applet.Applet;
import java.awt.Graphics;

public class AppletExample extends Applet {


public void paint(Graphics g) {
g.drawString("Hello, Applet!", 50, 50);
}
}

<applet code="AppletExample.class" width="300"


height="200"></applet>
AWT Controls

AWT Controls: Key Points

Definition:
1. AWT controls are pre-defined classes in the java.awt package that
enable the creation of interactive graphical user interfaces (GUIs).
Purpose:
2. They serve as basic building blocks for user interaction, such as
entering data, making selections, and triggering events.
Class Button

Definition: Represents a push button that triggers an ActionEvent when clicked.


Buttons are used to perform actions in a GUI application.
Important Methods:
setLabel(String label): Sets the text on the button.
getLabel(): Retrieves the button's text.
addActionListener(ActionListener l): Registers an action listener to
handle button events.
Constructor:
Button(): Creates an empty button.
Button(String label): Creates a button with specified text.
Class Label
Definition: A non-editable text display used to describe other GUI
components like text fields or buttons. Labels can display messages or
provide instructions.
Important Methods:
setText(String text): Changes the label's text.
getText(): Returns the current text of the label.
setAlignment(int alignment): Sets the alignment (LEFT,
CENTER, RIGHT).
Constructor:
Label(): Creates an empty label.
Label(String text): Creates a label with specified text.
Class CheckBox
Definition: Represents a checkbox that allows the user to select or
deselect an option. It can be standalone or grouped for mutual
exclusivity.
Important Methods:
getState(): Returns the current state (selected or deselected).
setState(boolean state): Sets the state of the checkbox.
addItemListener(ItemListener l): Adds an item listener for
state
changes.
Constructor:
Checkbox(): Creates an empty checkbox.
Checkbox(String label): Creates a checkbox with specified text.
Class CheckBoxGroup

Definition: Groups checkboxes to make them mutually


exclusive, meaning only one checkbox can be selected at a
time.
Important Methods:
getSelectedCheckbox(): Returns the currently
selected checkbox in the group.
setSelectedCheckbox(Checkbox cb): Sets the
selected checkbox.
Constructor:
CheckboxGroup(): Creates a new checkbox group.
Class Choice

Definition: A drop-down list for selecting a single item from


multiple options. Useful for compact item selection.
Important Methods:
add(String item): Adds an item to the choice list.
getSelectedItem(): Retrieves the currently selected item.
getItem(int index): Gets the item at the specified index.
Constructor:
Choice(): Creates an empty drop-down list.
Class List

Definition: Displays multiple items, allowing single or multiple selections. Suitable


for displaying lists with scroll support.
Important Methods:
add(String item): Adds an item to the list.
getSelectedItem(): Returns the selected item.
remove(String item): Removes the specified item.
Constructor:
List(): Creates an empty list.
List(int rows): Creates a list with the specified number of visible rows.
Class TextField

Definition: Allows single-line text input, often used for data entry
or searching.
Important Methods:
setText(String text): Sets the text in the field.
getText(): Retrieves the entered text.
setEditable(boolean editable): Enables or disables
editing. Constructor:
TextField(): Creates an empty text field.
TextField(int columns): Creates a text field with specified
width.
Class TextArea

Definition: A multi-line editable text area for longer text input. Important
Methods:
append(String str): Appends text to the text area.
setText(String text): Sets the content of the text area.
getText(): Retrieves the current content.
Constructor:
TextArea(): Creates an empty text area.
TextArea(int rows, int columns): Creates a text area with
specified dimensions.
Class Panel

Definition: A container for grouping components, often used to


create complex layouts by nesting panels.
Important Methods:
add(Component comp): Adds a component to the panel.
setLayout(LayoutManager mgr): Sets the layout manager
for the panel.
getComponents(): Retrieves all components in the panel.
Constructor:
Panel(): Creates an empty panel.
Layout Managers

Definition: Layout managers are responsible for


arranging components in containers based on specific
rules, ensuring a structured and responsive GUI.
Purpose: Simplify component placement and resizing in a
platform-independent way.
Class FlowLayout
Definition: Arranges components in a left-to-right flow, wrapping to the
next line when there is no space. It is the default layout for Panel.
Important Methods:
setAlignment(int align): Sets the alignment (LEFT, CENTER,
RIGHT).
setHgap(int hgap): Sets the horizontal gap between components.
setVgap(int vgap): Sets the vertical gap between components.
Constructors:
FlowLayout(): Creates a centered flow layout with default gaps.
FlowLayout(int align): Creates a flow layout with specified
alignment.
FlowLayout(int align, int hgap, int vgap): Creates a flow
layout with specified alignment and gaps.
Alignment Constants of FlowLayout:

FlowLayout.LEFT (Value: 0): Aligns components to


the left.
FlowLayout.CENTER (Value: 1): Centers
components (default alignment).
FlowLayout.RIGHT (Value: 2): Aligns components to
the right.
Class BorderLayout
Definition: Divides the container into five regions: North, South, East, West, and
Center, where each region can hold one component.
Important Methods:
addLayoutComponent(String name, Component comp): Adds a component
to a specific region.
getLayoutAlignmentX(Container target): Gets the alignment along the
x-axis.
getLayoutAlignmentY(Container target): Gets the alignment along the y-axis.
Constructors:
BorderLayout(): Creates a border layout with default gaps.
BorderLayout(int hgap, int vgap): Creates a border layout with
specified horizontal and vertical gaps.
BorderLayout

Region Constants:

BorderLayout.NORTH: Represents the top region.


BorderLayout.SOUTH: Represents the bottom region.
BorderLayout.EAST: Represents the right region.
BorderLayout.WEST: Represents the left region.
BorderLayout.CENTER: Represents the center region.
Class GridLayout
Definition: Divides the container into equal-sized grid cells where each
component takes one cell. Components are added row by row.
Important Methods:
setRows(int rows): Sets the number of rows in the grid.
setColumns(int cols): Sets the number of columns in the grid.
setHgap(int hgap): Sets the horizontal gap between cells.
setVgap(int vgap): Sets the vertical gap between cells.
Constructors:
GridLayout(): Creates a grid layout with one row and one column.
GridLayout(int rows, int cols): Creates a grid layout with specified rows
and columns.
GridLayout(int rows, int cols, int hgap, int vgap): Creates a grid layout
with specified rows, columns, and gaps.
Class CardLayout
Definition: Stacks components like a deck of cards, displaying only one
at a time. Used for creating wizard-style or tabbed interfaces.
Important Methods:
first(Container parent): Displays the first card.
next(Container parent): Displays the next card.
previous(Container parent): Displays the previous
card.
show(Container parent, String name): Displays the card with
the specified name.
Constructors:
CardLayout(): Creates a card layout with no gaps.
CardLayout(int hgap, int vgap): Creates a card layout with
specified gaps.
Class GridBagLayout

Definition: A flexible grid-based layout where rows and columns can have
variable sizes, and components can span multiple rows or columns.
Important Methods:
setConstraints(Component comp, GridBagConstraints
gbc): Sets constraints for a component.
getLayoutAlignmentX(Container parent): Gets the alignment
along the x-axis.
getLayoutAlignmentY(Container parent): Gets the alignment
along the y-axis.
Constructors:
GridBagLayout(): Creates a grid bag layout with default constraints.
GridBagLayout

Constraint Constants (used with GridBagConstraints):


GridBagConstraints.RELATIVE: Places the component relative to the
previous one.
GridBagConstraints.REMAINDER: Ends the row for the component.
GridBagConstraints.NONE: No resizing.
GridBagConstraints.HORIZONTAL: Resizes the component horizontally.
GridBagConstraints.VERTICAL: Resizes the component vertically.
GridBagConstraints.BOTH: Resizes both horizontally and vertically.
Anchor Constants: Determines component alignment when resizing
space is larger. Examples include
GridBagConstraints.NORTH, GridBagConstraints.SOUTH,
GridBagConstraints.WEST, GridBagConstraints.CENTER, etc.
Working with Menu and
MenuBar

Menus in AWT
Menus in Java AWT are created using the classes Menu,
MenuBar, and MenuItem. Below is the detailed explanation of their
constructors and methods:
Class MenuBar
Description: The MenuBar class is used to create a menu bar that holds
menus. A menu bar can be added to a frame using the setMenuBar()
method.
Constructors:
1. MenuBar(): Creates an empty menu bar.

Methods:
1. add(Menu m): Adds a menu to the menu bar.
2. remove(int index): Removes the menu at the specified index.
3. remove(Menu m): Removes the specified menu.
4. getMenu(int index): Returns the menu at the specified index.
5. getMenuCount(): Returns the number of menus in the menu bar.
6. setHelpMenu(Menu m): Sets the help menu (usually the last menu on the
right).
Class Menu

Description: The Menu class represents a pull-down menu that contains menu
items.
Constructors:
1. Menu(): Creates an empty menu with no label.
2. Menu(String label): Creates a menu with the specified label.
3. Menu(String label, boolean tearOff): Creates a menu with the specified label
and a tear-off functionality.
Methods of Menu :

1. add(String label): Adds a menu item with the specified label.


2. add(MenuItem item): Adds the specified menu item.
3. add(Menu submenu): Adds a submenu to the menu.
4. remove(int index): Removes the menu item at the specified index.
5. remove(MenuComponent item): Removes the specified menu component.
6. insert(String label, int index): Inserts a menu item at the specified index.
7. insert(MenuItem item, int index): Inserts the specified menu item at the
specified index.
8. getItem(int index): Returns the menu item at the specified index.
9. getItemCount(): Returns the number of items in the menu.
Class MenuItem

Description: The MenuItem class represents an item in a menu. It can be


selected by the user to perform an action.
Constructors:
1. MenuItem(): Creates a menu item with no label.
2. MenuItem(String label): Creates a menu item with the specified label.
3. MenuItem(String label, MenuShortcut s): Creates a menu item with the
specified label and shortcut.
Methods of class MenuItem:

1. setLabel(String label): Sets the label of the menu item.


2. getLabel(): Returns the label of the menu item.
3. setEnabled(boolean enabled): Enables or disables the menu item.
4. isEnabled(): Checks if the menu item is enabled.
5. addActionListener(ActionListener l): Adds an action listener to the menu item.
6. removeActionListener(ActionListener l): Removes the action listener from the
menu item.
7. getActionCommand(): Returns the command string associated with the menu
item.
8. setActionCommand(String command): Sets the command string for the menu
item.
PROGRAM
import java.awt.*;
import java.awt.event.*;
fileMenu.add(newFile);
fileMenu.add(openFile);
fileMenu.addSeparator();
public class MenuExample {
public static void main(String[] args) { fileMenu.add(exit);
Frame frame = new Frame("Menu Example"); menuBar.add(fileMenu);
frame.setSize(400, 300); menuBar.add(editMenu);
frame.setMenuBar(menuBar);
MenuBar menuBar = new MenuBar();
exit.addActionListener(e -> System.exit(0));
frame.setVisible(true);
Menu fileMenu = new Menu("File");
}
Menu editMenu = new Menu("Edit");
-------------------------------------
}
MenuItem newFile = new MenuItem("New"); | File Edit |
MenuItem openFile = new MenuItem("Open"); -------------------------------------
MenuItem exit = new MenuItem("Exit"); | New |
| |
Open
| -------------------------------- |
| Exit |
Working with FileDialog
FileDialog is a class in AWT that provides a standard file selection dialog box for
opening or saving files. It is used to allow users to select files in a GUI application.

Constructors:
1. FileDialog(Frame parent):Creates a file dialog with the specified parent window
(frame) for selecting files.
2. FileDialog(Frame parent, String title):Creates a file dialog with the
specified parent window and title for the dialog box.
3. FileDialog(Frame parent, String title, int mode):Creates a file dialog with
the specified parent window, title, and mode (either FileDialog.LOAD or
FileDialog.SAVE).
FileDialog.LOAD: For loading a file.
FileDialog.SAVE: For saving a file.
Important Methods:

1. setDirectory(String dir):Sets the initial directory where the file dialog


will open.
2. setFile(String filename):Sets the initial file name that appears in the file
dialog.
3. setMode(int mode):Sets the mode of the file dialog: FileDialog.LOAD for
loading files, FileDialog.SAVE for saving files.
4. setTitle(String title):Sets the title of the file dialog box.
5. getFile():Returns the name of the selected file (if any), or null if no file
was selected.
6. getDirectory():Returns the directory selected in the file dialog.
7. show():Displays the file dialog and waits for the user to select a file. This
method is deprecated in favor of setVisible(true) in modern Java versions.
Origin of Swing

Swing is a GUI (Graphical User Interface) toolkit in Java that was


developed as a part of Java Foundation Classes (JFC). It was
introduced to overcome the limitations of AWT (Abstract Window
Toolkit), which was Java’s original GUI library. Swing is now the
standard for building rich, modern, and platform- independent GUI
applications in Java.
Problems in AWT Components

● Platform Dependency
● Limited Customizability
● Lack of Advanced GUI Components
● Poor Layout Management
● Inconsistent Event Handling
● Limited Look and Feel
● No Support for Modern GUI Features
● Limited Multi-threading Support
● Lack of Pluggable Look and Feel
● Limited Support for Event Dispatching
Features of Swing Components

● Lightweight Components
● Pluggable Look and Feel
● Rich Set of GUI Components
● Model-View-Controller (MVC) Architecture
● Improved Event Handling
● Customizable Components
● Double Buffering
● Platform Independence
● Better Layout Management
● Support for Advanced GUI Features
Difference Between AWT and Swing Components
Swing components classes

Swing components are the building blocks for creating rich and interactive
graphical user interfaces in Java. They provide a more flexible and customizable
approach to building UIs compared to AWT components.

Definition:
Swing components are lightweight, meaning they are drawn entirely by Java rather
than relying on native operating system components. Swing allows developers to
create highly interactive, visually appealing, and platform- independent GUI
applications. It supports a wide variety of components and layouts, with better
control over the look and feel of the application.
class JComponent
Definition:
The base class for all Swing components, providing common properties and methods.
Constructors:
JComponent(): Initializes a new JComponent object.
Methods:
setVisible(boolean aFlag): Sets the visibility of the component.
setSize(int width, int height): Sets the size of the component.
setLayout(LayoutManager manager): Sets the layout manager for the
component.
repaint(): Requests that the component be repainted.
setBackground(Color bg): Sets the background color of the component.
Constants:
UIResource: A marker interface indicating that a component's UI delegate is an
UIResource.
class JFrame
Definition:
A top-level container used to create a window for Swing applications.
Constructors:
JFrame(): Creates a new JFrame object with a default title.
JFrame(String title): Creates a new JFrame object with the specified title.
Methods:
setVisible(boolean b): Makes the frame visible or invisible.
setSize(int width, int height): Sets the size of the frame.
setTitle(String title): Sets the title of the frame.
setDefaultCloseOperation(int operation): Sets the operation that occurs
when the user closes the frame.
setLayout(LayoutManager layout): Sets the layout manager for the frame.
Constants:
JFrame.EXIT_ON_CLOSE: Specifies that the application should
exit when the user closes the window.
JFrame.HIDE_ON_CLOSE: Specifies that the frame should be
hidden when the user closes the window.
class JApplet
Definition:
Swing-based applet used for applet-based applications (though
applets are outdated).
Constructors:
JApplet(): Creates a new JApplet object.
Methods:
init(): Initializes the applet (called once during the applet's lifecycle).
start(): Starts the applet (called when the applet is visible).
stop(): Stops the applet (called when the applet is no longer visible).
destroy(): Destroys the applet (called when the applet is unloaded).

Constants: None specific to JApplet.


class ImageIcon
Definition:ImageIcon is used to load and display images as icons in
Swing components, such as buttons and labels.
Constructors:
ImageIcon(): Creates an empty ImageIcon object.
ImageIcon(String filename): Creates an ImageIcon from an image
file located at the specified file path.
ImageIcon(URL location): Creates an ImageIcon from an image
located at the specified URL.
ImageIcon(Image image): Creates an ImageIcon using an Image
object.
ImageIcon(String filename, String description): Creates an
ImageIcon from the image file with an optional description.
Methods of ImageIcon:

getImage(): Returns the Image object used by this ImageIcon.


getDescription(): Returns the description of the ImageIcon.
setDescription(String description): Sets the description of the
ImageIcon.
paintIcon(Component c, Graphics g, int x, int y): Paints the icon at the
specified location.

Constants:None specific to ImageIcon.


class JButton
Definition:Represents a button component that can trigger actions when
clicked.
Constructors:
JButton(): Creates a new JButton with no text or icon.
JButton(String text): Creates a new JButton with the specified text.
JButton(Icon icon): Creates a new JButton with the specified icon.
JButton(String text, Icon icon): Creates a new JButton with the specified text
and icon.
Methods:
addActionListener(ActionListener l): Adds an action listener to the button.
setText(String text): Sets the text of the button.
setIcon(Icon icon): Sets the icon of the button.
setEnabled(boolean b): Enables or disables the button.
class JLabel

Definition:Displays text or images.


Constructors:
JLabel(): Creates a new JLabel with no text or image.
JLabel(String text): Creates a new JLabel with the specified
text.
JLabel(Icon icon): Creates a new JLabel with the specified
icon.
JLabel(String text, Icon icon, int
horizontalAlignment):Creates a new JLabel with text, icon, and
alignment.
Methods:
setText(String text): Sets the text of the label.
setIcon(Icon icon): Sets the icon of the label.
setHorizontalAlignment(int alignment): Sets the
horizontal alignment of the label.
setVerticalAlignment(int alignment): Sets the
vertical alignment of the label.
Constants:
SwingConstants.LEFT: Left-aligned text.
SwingConstants.CENTER: Center-aligned text.
SwingConstants.RIGHT: Right-aligned text.
class JTextField
Definition:A single-line text field for editable input.
Constructors:
JTextField(): Creates an empty JTextField.
JTextField(String text): Creates a JTextField with the specified text.
JTextField(int columns): Creates an empty JTextField with a specified number of
columns.
JTextField(String text, int columns): Creates a JTextField with specified text
and column count.
Methods:
setText(String text): Sets the text of the text field.
getText(): Returns the current text in the text field.
setColumns(int columns): Sets the number of columns in the text field.
addActionListener(ActionListener l): Adds an action listener to the text field.
class JTextArea
Definition: A multi-line text area for editable input.
Constructors:
JTextArea(): Creates an empty JTextArea.
JTextArea(String text): Creates a JTextArea with the specified text.
JTextArea(int rows, int columns): Creates a JTextArea with specified number
of rows and columns.
JTextArea(String text, int rows, int columns): Creates a JTextArea with
specified text, rows, and columns.
Methods:
setText(String text): Sets the text of the text area.
getText(): Returns the current text in the text area.
setRows(int rows): Sets the number of rows.
setColumns(int columns): Sets the number of
columns. append(String str): Appends text to the text
area.
class JComboBox
Definition: A combo box (drop-down list) that allows selection of a single item.
Constructors:
JComboBox(): Creates an empty combo box.
JComboBox(Object[] items): Creates a combo box with the specified items.
JComboBox(Vector<?> items): Creates a combo box with the
specified vector of items.
Methods:
addItem(Object anItem): Adds an item to the combo
box. setSelectedItem(Object anObject): Selects an
item. getSelectedItem(): Gets the selected item.
addActionListener(ActionListener l): Adds an action listener to the
combo box.
class JCheckBox
Definition: A check box that can be checked or unchecked.
Constructors:
JCheckBox(): Creates an empty check box.
JCheckBox(String text): Creates a check box with specified text.
JCheckBox(String text, boolean selected): Creates a check box
with specified text and selected state.
Methods:
setSelected(boolean b): Sets the selected state of the check box.
getSelected(): Returns the selected state of the check box.
addActionListener(ActionListener l): Adds an action listener to
the
check box.
class JRadioButton
Definition: A radio button that is part of a button group, where only one button
can be selected.
Constructors:
JRadioButton(): Creates an empty radio button.
JRadioButton(String text): Creates a radio button with specified text.
JRadioButton(String text, boolean selected): Creates a radio button
with specified text and selected state.
Methods:
setSelected(boolean b): Sets the selected state of the radio button.
getSelected(): Returns the selected state of the radio button.
addActionListener(ActionListener l): Adds an action listener to the
radio
button.
Advanced Swing components classes

JTabbedPane : Allows tabbed navigation.


JScrollPane : Adds scrollable functionality.
JTree : Displays hierarchical data.
JTable : Displays tabular data.
JProgressBar : Indicates progress of a task.
JToolTip : Provides tooltips for components.
JTabbedPane

Definition: JTabbedPane allows tabbed navigation by adding tabs


with components, enabling multiple panels to be displayed within
a single window.
Constructors:
JTabbedPane(): Creates a new empty JTabbedPane.
JTabbedPane(int tabPlacement): Creates a new
JTabbedPane with the specified tab placement (TOP, BOTTOM,
LEFT, RIGHT).
JTabbedPane(int tabPlacement, int
tabLayoutPolicy): Creates a new JTabbedPane with specified
tab placement and layout policy (SCROLL_TAB_LAYOUT or
WRAP_TAB_LAYOUT).
Methods:
addTab(String title, Component component): Adds a tab with the specified title
and component.
addTab(String title, Icon icon, Component component): Adds a tab with
the specified title, icon, and component.
setSelectedIndex(int index): Selects the tab at the given index.
getSelectedIndex(): Returns the index of the selected tab.
setTabPlacement(int tabPlacement): Sets the placement of the tabs.
Constants:
JTabbedPane.TOP: Positions tabs at the top.
JTabbedPane.BOTTOM: Positions tabs at the bottom.
JTabbedPane.LEFT: Positions tabs on the left.
JTabbedPane.RIGHT: Positions tabs on the right.
JTabbedPane.SCROLL_TAB_LAYOUT: Enables scrolling for tabs that do not fit in the
available space.
JTabbedPane.WRAP_TAB_LAYOUT: Enables wrapping of tabs if they do not fit.
JScrollPane

Definition: JScrollPane adds scrollable functionality to any container or


component, allowing the user to scroll through the content.
Constructors:
JScrollPane(): Creates an empty scroll pane.
JScrollPane(Component view): Creates a scroll pane containing
the specified component.
JScrollPane(int vsbPolicy, int hsbPolicy): Creates a scroll pane
with the specified vertical and horizontal scroll bar policies.
Methods:
setViewportView(Component view): Sets the component to be displayed
in the viewport of the scroll pane.
getVerticalScrollBar(): Returns the vertical scroll bar of the scroll pane.
getHorizontalScrollBar(): Returns the horizontal scroll bar of the scroll pane.
Constants:
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED: Vertical scrollbar appears
when needed.
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED: Horizontal scrollbar
appears when needed.
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS: Vertical scrollbar is always
visible. JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS: Horizontal scrollbar is
always visible.
JScrollPane.VERTICAL_SCROLLBAR_NEVER: Vertical scrollbar is never
visible. JScrollPane.HORIZONTAL_SCROLLBAR_NEVER: Horizontal scrollbar
is never visible.
JTree

Definition: JTree is used to display hierarchical data (like a directory structure or


organization chart) in a tree-like format.
Constructors:
JTree(): Creates a new empty JTree.
JTree(TreeModel newModel): Creates a tree with the specified tree model.
JTree(Object[] value): Creates a tree from an array of objects.
JTree(Vector<?> value): Creates a tree from a vector of objects.
Methods:
setModel(TreeModel newModel): Sets the tree model for the tree.
getModel(): Returns the tree model.
setSelectionRow(int row): Selects a specific row.
getPathForRow(int row): Returns the tree path for a given row index.
expandRow(int row): Expands the node at the specified row.
JTable

Definition: JTable is used to display tabular data in a grid format, allowing


interaction such as selecting rows and columns.
Constructors:
JTable(): Creates a new empty JTable.
JTable(Object[][] rowData, Object[] columnNames): Creates a table with
the given row data and column names.
JTable(TableModel dm): Creates a table using a specific TableModel.
Methods:
setModel(TableModel model): Sets the table model.
getModel(): Returns the current table model.
setColumnSelectionAllowed(boolean flag): Allows column selection if true.
getSelectedRow(): Returns the index of the selected row.
getSelectedColumn(): Returns the index of the selected column.
Constants:
JTable.AUTO_RESIZE_OFF: Disables auto-resizing of columns.
JTable.AUTO_RESIZE_ALL_COLUMNS: Automatically resizes all columns to
fit the table.
JTable.AUTO_RESIZE_LAST_COLUMN: Automatically resizes only the last
column.
JProgressBar
Constructors:
JProgressBar(): Creates a new JProgressBar with default values.
JProgressBar(int min, int max): Creates a new JProgressBar with specified minimum
and maximum values.
JProgressBar(int orientation, int min, int max): Creates a new JProgressBar
with specified orientation, minimum, and maximum values.
Methods:
setMinimum(int min): Sets the minimum value of the progress bar.
setMaximum(int max): Sets the maximum value of the progress bar.
setValue(int value): Sets the current value of the progress bar.
setString(String string): Sets the string that appears inside the progress bar.
setStringPainted(boolean b): Determines whether the string inside the progress bar is
painted.
Constants:
JProgressBar.HORIZONTAL: Horizontal orientation.
JProgressBar.VERTICAL: Vertical orientation.
JToolTip

Definition: JToolTip provides a small pop-up window containing helpful text


that appears when the user hovers over a component.

Constructors:
JToolTip(): Creates a new JToolTip object.
Methods:
setTipText(String tipText): Sets the text that appears in the tooltip.
getTipText(): Returns the text in the tooltip. setComponent(Component
component): Sets the component that the tooltip is associated with.
Importance of Event Handling

Event handling is crucial in creating interactive and responsive


applications. It enables applications to respond to user actions, such as
clicks, key presses, and mouse movements, by triggering specific
behaviors. This interaction is managed using the Delegation Event
Model, where events are generated by sources (components) and
handled by listeners (objects). Event handling improves the user
experience by making applications dynamic and functional.
Event Classes

ActionEvent: Button clicks or menu actions.


ItemEvent: Checkbox or choice selection changes.
KeyEvent: Key presses.
MouseEvent: Mouse actions.
TextEvent: Changes in text fields.
WindowEvent: Window actions like close or minimize.
ActionEvent
Constructors
1. ActionEvent(Object source, int id, String command)
2. Creates an ActionEvent with a specified source, event ID, and action command.
3. ActionEvent(Object source, int id, String command, long when, int modifiers)
4. Creates an ActionEvent with additional time and modifier information.
Methods
1. getActionCommand():Returns the command string associated with the action.
2. getModifiers():Returns the modifier keys pressed during the event.
3. getWhen():Returns the timestamp of when the event occurred.
Constants
CTRL_MASK
ALT_MASK
META_MASK
SHIFT_MASK
ItemEvent

Constructors
1. ItemEvent(ItemSelectable source, int id, Object item, int stateChange)
2. Creates an ItemEvent for the specified source, ID, item, and state change.
Methods
1. getItem(): Returns the affected item.
2. getItemSelectable(): Returns the component that generated the event.
3. getStateChange(): Returns the state change (selected or deselected).
Constants
SELECTED: Indicates the item was selected.
DESELECTED: Indicates the item was deselected.
Integer constant : ITEM_STATE_CHANGED
KeyEvent

Types of KeyEvents in KeyEvent Class


1. KEY_PRESSED
Triggered when a key is pressed down.
Constant value: KeyEvent.KEY_PRESSED (int value: 401).
2. KEY_RELEASED
Triggered when a key is released after being pressed.
Constant value: KeyEvent.KEY_RELEASED (int value: 402).
3. KEY_TYPED
Triggered when a key is typed (pressed and released),
generating a Unicode character.
Constant value: KeyEvent.KEY_TYPED (int value: 400).
Methods
1. getKeyCode()
2. Returns the key code.
3. getKeyChar()
4. Returns the key character.
5. isActionKey()
6. Checks if the key is an action key.

Constants
KEY_FIRST: The first integer ID for key events.
KEY_LAST: The last integer ID for key events.
VK_A - VK_Z: Key codes for alphabet keys.
MouseEvent

MOUSE_CLICKED: Triggered when a mouse button is clicked (pressed and released) on a


component.
MOUSE_PRESSED: Triggered when a mouse button is pressed on a component.
MOUSE_RELEASED: Triggered when a mouse button is released on a component.
MOUSE_MOVED: Triggered when the mouse is moved over a component without
pressing any buttons.
MOUSE_ENTERED: Triggered when the mouse pointer enters the bounds of a
component.
MOUSE_EXITED: Triggered when the mouse pointer exits the bounds of a component.
MOUSE_DRAGGED: Triggered when the mouse is moved while a button is pressed
(dragging).
MOUSE_WHEEL: Triggered when the mouse wheel is rotated.
Methods
1. getX(), getY(): Returns the X and Y coordinates of the mouse event.
2. getClickCount(): Returns the number of clicks.
3. isPopupTrigger(): Checks if the event triggered a popup menu.

Constructors
1. MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int
clickCount, boolean popupTrigger)
2. Creates a MouseEvent with specified coordinates, click count, and popup
trigger status.
TextEvent

Constructors
1. TextEvent(Object source, int id)
2. Creates a TextEvent with the specified source and ID.
Methods
1. getSource()
2. Returns the object that generated the event.
Constants
TEXT_FIRST: The first integer ID for text events.
TEXT_LAST: The last integer ID for text events.
Integer constant : TEXT_VALUE_CHANGED
WindowEvent
Types of Window Events in WindowEvent Class

WINDOW_OPENED: Triggered when a window is opened.


WINDOW_CLOSING: Triggered when a window is in the process of closing.
WINDOW_CLOSED: Triggered after a window has been closed.
WINDOW_ICONIFIED: Triggered when a window is minimized (iconified).
WINDOW_DEICONIFIED: Triggered when a window is restored from a
minimized state.
WINDOW_ACTIVATED: Triggered when a window becomes the active window.
WINDOW_DEACTIVATED: Triggered when a window is no longer the active
window.
WINDOW_GAINED_FOCUS: Triggered when a window gains keyboard focus.
WINDOW_LOST_FOCUS: Triggered when a window loses keyboard focus.
WINDOW_STATE_CHANGED: Triggered when the state of a window changes,
such as maximized or minimized.
Constructors
1. WindowEvent(Window source, int id): Creates a WindowEvent for the
specified source and event ID.
2. WindowEvent(Window source, int id, Window opposite): Creates a
WindowEvent with the opposite window.
Methods
1. getWindow(): Returns the window where the event occurred.
2. getOppositeWindow():Returns the opposite window, if applicable.
3. getOldState()
4. getNewState()
Constants
WINDOW_OPENED: Indicates the window was opened.
WINDOW_CLOSING: Indicates the window is being closed.
WINDOW_CLOSED: Indicates the window was closed.
Event Listener Interfaces

Event Listener Interfaces

ActionListener: Handles ActionEvent.


ItemListener: Handles ItemEvent.
KeyListener: Handles KeyEvent. MouseListener:
Handles MouseEvent. MouseMotionListener:
Tracks mouse motion. TextListener: Handles
TextEvent.
ActionListener
ActionListener
Method:
void actionPerformed(ActionEvent e): Triggered when an action occurs (e.g.,
button click).

ItemListener
ItemListener
Method:
void itemStateChanged(ItemEvent e): Triggered when an item's state
changes (e.g., checkbox selection).
KeyListener

Methods:
void keyPressed(KeyEvent e): Triggered when a key is pressed. void
keyReleased(KeyEvent e): Triggered when a key is released.
void keyTyped(KeyEvent e): Triggered when a key is pressed and released,
generating a character.
MouseListener

Methods:
void mouseClicked(MouseEvent e): Triggered when a mouse button is
clicked.
void mousePressed(MouseEvent e): Triggered when a mouse button is
pressed.
void mouseReleased(MouseEvent e): Triggered when a mouse button is
released.
void mouseEntered(MouseEvent e): Triggered when the mouse enters a
component.
void mouseExited(MouseEvent e): Triggered when the mouse exitsa
component.
MouseMotionListener

Methods:
void mouseMoved(MouseEvent e): Triggered when the mouse is moved. void
mouseDragged(MouseEvent e): Triggered when the mouse is moved while a
button is pressed.

TextListener

Method:
void textValueChanged(TextEvent e): Triggered when the
value of a text component changes.
Thankyou :)

You might also like