0% found this document useful (0 votes)
44 views83 pages

Unit 2

This is a lecture notes provided by our teacher

Uploaded by

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

Unit 2

This is a lecture notes provided by our teacher

Uploaded by

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

Java Swing

Unit II
By Ghazala Khan
In java, we can make
• console based application
• Windows/ GUI-based applications (but it is difficult)

Using Java Swings, you can make a complete GUI


application that includes a database.

Eg. VLC is a GUI/ Desktop Application.


We can make such applications using Java
JFC- Package (contains Java Swing API)
API - pre made classes and code (has all classes needed to create
GUI)
Package: javax.swing
● Contains classes and interfaces such as JFrame, JButton, JPanel,
etc.
● Package Usage: The javax.swing package is imported at the top.

API: Swing API


● Provides the necessary methods and constructors to create and
manage graphical user interfaces. For example, JFrame has methods
like setSize(), setVisible(), and add().
● API Usage: The JFrame and JButton classes are used to create and
manipulate GUI components.
● A package can contain multiple APIs. For example, the java.awt package
contains the AWT API which provides the necessary tools to create
graphical user interfaces.
● An API can be spread across multiple packages. For instance, the Java
Collections Framework API includes classes from java.util,
java.util.concurrent, and other packages.
Introduction to Swing
Swing components are called lightweight
components.
If you create a button using AWT on Windows and then run
the same application on macOS, the button may look different
on each system because it uses the native button widgets of
each operating system.
In contrast to Swing components, which are rendered entirely
in Java and have a consistent appearance across platforms,
AWT components are "heavyweight" because they rely on the
native GUI components of the operating system. This can
lead to variations in appearance and behavior depending on
the OS you are using.
Introduction to Swing
• Package : javax.swing.*
• Swing is set of classes which provides more powerful
and flexible GUI components as compare to AWT to
create Java based Front End/ GUI components.
• Built on top (child) of AWT API and acts as
replacement of AWT API.
• Swing component follows Model-View-Controller.
• Swing Components are implemented using Java and
so they are platform independent.
• Contain more components than AWT.
Introduction to Swing
Swing Features
• Borders we can draw borders in many different styles around
components using the setBorder( ) method.
• Graphics Debugging We can use setDebuggingGraphicsOptions
method to set up graphics debugging which means, that you can
watch each line as its drawn and make it flash.
• Easy mouseless operation: It is easy to connect keystrokes to
components.
• Tooltips We can use the setToolTipText method of JComponent to
give components a tooltip, one of those small windows that appear
when the mouse hovers over a component and gives explanatory
text.
• Easy Scrolling We can connect scrolling to various components-
something that was impossible in AWT.
• Pluggable look and feel: We can set the appearance of applets and
applications to one of three standard looks. Windows, Motif (Unix)
or Metal (Standard swing look).
• New Layout Managers Swing introduces the BoxLayout and
OverlayLayout layout managers.
MVC Architecture
• Software design pattern for software development.
• Model:
• Major function of this layer to maintain the data.
• Database and logic.

• View:
• Used to display full or partial data.
• User Interface

• Controller:
• Control the interaction and communication between Model and view.
• Communication logic/integration logic

Top level: Controller


Middle level: View
Bottom level: Model
Difference Between AWT & Swing
• AWT uses Applet and Frame while Swing uses JApplet and JFrame
for GUI.
• AWT is platform dependent code while Swing code is platform
independent.
• AWT components are Heavyweight where as Swing components are
Lightweight.
• Swing has bigger collection of classes and interfaces as compare
to AWT.
• In Swing, extra feature for Button: Provide Image.
• Swing provides: Tree, Table, Scrollpanes, Tabbedpanes, etc. new
features.
• AWT does not follow MVC.
• Awt doesn’t support pluggable look and feel, but Swing does.
(cannot change look, colour, visual appeal, properties in AWT)
(Look=appearance, feel=behaviour)
JApplet
• Fundamental to Swing is the JApplet class, which extends
Applet.
• Applets that use Swing must be subclasses of JApplet.
• JApplet is rich with functionality that is not found in
Applet.
• Top level swing container- not derived from JComponent.
• JApplets have the same lifecycle methods, init(), start(), stop()
and destroy(), you need to override only those methods used
by Applet.
Painting in JApplet
What is the EDT? The Event Dispatching Thread (EDT) is a special thread in Java responsible for
handling all the event-driven tasks, such as responding to user interactions (e.g., button clicks, mouse
movements) and updating the graphical user interface (GUI) components.
Swing components are not thread-safe, meaning that updating or interacting with them outside the
EDT can cause unpredictable behavior. Therefore, all interactions with Swing components should be
done on the EDT.
JComponent and paint: All Swing components inherit the paint method from the JComponent class.
This method is responsible for the component's appearance on the screen. When a component needs
to be redrawn, the paint method is called by the Swing framework.

paintComponent(Graphics g):

● It is responsible for painting the component's content (e.g., drawing shapes, images, text).

paintBorder(Graphics g):

This method paints the border of the component.


You can override this method if you need to customize the border's appearance.

paintChildren(Graphics g):

● This method is responsible for painting the component's child components (e.g., buttons, labels
that are contained within a panel).
Panes in JApplet
• JApplet supports various “panes,” such as the content
pane, the glass pane, and the root pane.
• Content is added by default to content pane.
Root Pane (JRootPane):
● Contains and manages the other panes mentioned below, main container for all
content in the JApplet. Gui components added to the root pane members rather
than the root pane itself.

Content Pane:
● You typically add your components to the content pane.
● Retrieve the content pane using getContentPane() and add
components.

EXTRA------------------------------------------------------------------------------------------------------
Glass Pane:
● An optional pane that sits on top of all other panes, useful for drawing or
handling input events in a way that affects the entire applet.
● getGlassPane().

Layered Pane:
Allows components to overlap, eg. adding pop-ups, dialogs. getLayeredPane()
Imagine you have a main drawing area, and you want to display a floating toolbar on
top of it.

Optional Menu Bar:


If your applet has a menu bar,
it can be set and managed using
setJMenuBar() and getJMenuBar().
**Extra**
DIFFERENCE

Glass Pane
Draw Over Everything: You can draw custom graphics (like shapes or
text) on this transparent sheet, and it will appear over all other
components such as add effects on top of everything (e.g., highlighting
an area).
Capture Events: It can capture and handle events (like mouse clicks)
before they reach other components underneath.

Layered Pane
Overlapping Components: If you need to create an interface with
overlapping components (e.g., a floating toolbar over a main panel).
Methods
• When adding a component to an instance of JApplet, do not
invoke the add( ) method of the applet instead, call add( ) for
the content pane of the JApplet object. contentPane.add(new
JButton("Click Me"));

• The content pane can be obtained (get your content) via the
method shown here:
• Container getContentPane( )

• add a component to a content pane- void add(comp)


Here, comp is the component to be added to the content pane.

Default layout is border layout.


JFrame

JFrame also has a JRootPane, which contains the same panes as


a JApplet.

Eg. when we add a button component, JButton class is


associated with it at the backend.
Methods of JFrame class
• The add( ) method of Container can be used to add a component to a
content pane - void add(comp)

EXIT_ON_CLOSE: Terminates the application.


DISPOSE_ON_CLOSE: Disposes of the frame but keeps the
application running.
HIDE_ON_CLOSE: Hides the frame without disposing of it.
DO_NOTHING_ON_CLOSE: Does nothing, allowing for custom
close operations.
Example to explain the difference
b/w EXIT and DISPOSE
Main Window: Contains a button to open a secondary window. ( For eg set
to EXIT_ON_CLOSE)
Secondary Window: Opens when you click the button in the Main Window.
(For eg set to DISPOSE_ON_CLOSE)

Secondary Window closes and frees its resources when the user closes it,
but the Main Window remains open and functional. You can still interact with
the Main Window even after the Secondary Window is closed.

When Main Window is closed, it terminates the entire application, including


any open Secondary Windows. The Java Virtual Machine (JVM) stops.Even
though secondary window uses DISPOSE_ON_CLOSE, it will not be
functional or visible if the Main Window is closed because the entire
application exits.
JPanel
JPanel is a lightweight container in Swing for
holding and organizing other GUI components.

JPanel is a flexible Swing container used to group


and arrange components like buttons and labels. It
uses layout managers to control component
placement and supports custom painting by
overriding the `paintComponent` method.
Commonly used in creating complex layouts
within a JFrame.
Icons
• An ImageIcon is a class used to display images within
Swing components such as JLabel, JButton, or
JOptionPane
• In Swing, icons are encapsulated by the ImageIcon class,
which paints an icon from an image.
• Two of its constructors are shown here:
• ImageIcon(String filename)
• ImageIcon(URL url)
• The first form uses the image in the file named filename.
• The second form uses the image in the resource identified
by url.
Icon getIcon() - obtain icon
void setIcon(Icon icon) - set icon
int getIconHeight( )
• Returns the height of the icon in pixels.
int getIconWidth( )
• Returns the width of the icon in pixels.
void paintIcon(Component comp, Graphics g, int x, int y)
• Paints the icon at position x,y on the graphics
context g. Additional information about the paint
operation can be provided in comp.

(The graphics context is used to draw the icon. It provides the


drawing surface and methods to render shapes, text, and images.)
Swing labels
• Swing labels are instances of the JLabel class, which extends
JComponent.
• It can display text and/or an icon.
• Some of its constructors are shown here:
• JLabel(Icon i)
• JLabel(String s)
• JLabel(String s, Icon i, int align)
• Here, s and i are the text and icon used for the label.
• The align argument is either LEFT, RIGHT, CENTER, LEADING OR
TRAILING, these are constants.
• Leading alignment positions content at the beginning of a line or container,
typically on the left in left-to-right languages.
• Trailing alignment positions content at the end of a line or container, typically
one the right in left-to-right languages.

• String getText( )
• void setText(String s)
• Icon getIcon( )
import java.awt.*;
import javax.swing.*;
/* <applet code="JLabelDemo" width=250 height=150> </applet> */
public class JLabelDemo extends JApplet
{
public void init()
{
//Retrieves the content pane of the JFrame.
//By default, the content pane is the primary container for all the components of a
JFrame. When you use methods like add(), you're adding components to this
content pane.
Container contentPane = getContentPane();
ImageIcon ii = new ImageIcon("IC.jpg");
JLabel jl = new JLabel("IC", ii, JLabel.CENTER);
//by default the label is on the right of the img
// (img+label) will both be in the center
contentPane.add(jl);
}
}
JComboBox
• Swing provides a combo box (a combination of a text field and a
dropdown list) through the JComboBox class, which extends JComponent.
• A combo box normally displays one entry. However, it can also display a
drop-down list that allows a user to select a different entry. We can also
type our selection into the text field.
• Generates an action event when user selects an item from the list, also
generates item event when the state of selection changes
• Constructors:
JComboBox( )
JComboBox(Vector v)- A Vector is a resizable array-like data structure
Vector<String> items = new Vector<>();
items.add("Apple"); items.add("Banana"); items.add("Cherry");
JComboBox(Objects obj[])- obj is the array of objects.
int[] numbers = new int[5];
• Items are added to the list of choices via the addItem( )
method:
• void addItem(Object obj)
• public void setEditable(boolean aFlag)
• You can specify whether the JComboBox field is editable or not
• public boolean isEditable()
• It returns true if the JComboBox is editable. By default, a combo
box is not editable.
• public void setMaximumRowCount(int count)
• It sets the maximum number of rows the JComboBox displays.
• Public void setSelectedItem(Object anObject)- anObject is tem
that will be default selected
• public void insertItemAt(Object anObject, int index)
• public void removeItem(Object anObject)
• public void removeItemAt(int anIndex)

(can add items only in mutable combobox)


Text Fields
• The Swing text field is encapsulated by the
JTextComponent class, which extends JComponent.
• It provides functionality that is common to Swing
text components.
• One of its subclasses is JTextField, which allows us
to edit one line of text.
• Some of its constructors are shown here:
• JTextField( )
• JTextField(int cols) //no. of characters
• JTextField(String s, int cols) // s can be a default
or predefined value that the user can change.
• JTextField(String s)
import java.awt.*;
import javax.swing.*;
/* <applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends Japplet {
JTextField jtf;
public void init() {
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
jtf = new JTextField(15);
contentPane.add(jtf);
}}
JButton
• The JButton class provides the functionality of a
push button.
• JButton allows an icon, string, or both to be
associated with the push button.
• Swing buttons are subclasses of the AbstractButton
class, which extends JComponent. AbstractButton
contains many methods that allow us to control the
behavior of buttons, check box and radio buttons.
• For example, we can define different icons that are
displayed for the component when it is disabled,
pressed, or selected.
• Another icon can be used as rollover icon, which is
displayed when the mouse is positioned over that
component.
JButton
• The JButton class provides the functionality of a
push button.
• JButton allows an icon, string, or both to be
associated with the push button.
• Some of its constructors are shown here:
• JButton(Icon i)
• JButton(String s)
• JButton(String s, Icon i)
Methods
• void setDisabledIcon(Icon di): If a button is not
interactive (disabled), this icon will be shown
instead of the regular icon
• void setPressedIcon(Icon pi)-When a user clicks
(presses) the button, this icon will appear, providing
visual feedback
• void setSelectedIcon(Icon si)-A checkbox showing a
tick mark icon when selected
• void setRolloverIcon(Icon ri)- button changing its
icon to a highlighted version when hovered over.
• String getText( )
• void setText(String s)
• Concrete subclasses of AbstractButton generate
action events when they are pressed. Listeners
register and un-register for these events via the
methods shown here:
• void addActionListener(ActionListener al)
• void removeActionListener(ActionListener al)
• Here, al is the action listener.
JToggle Button
JCheckBox
• The JCheckBox class, which provides the functionality of a
check box, is a concrete implementation of AbstractButton.
• It is immediate super-class is JToggleButton, which
provides support for two-state buttons.
• Some of its constructors are shown here:
• JCheckBox(Icon i)
• JCheckBox(Icon i, boolean state)
• JCheckBox(String s)
• JCheckBox(String s, boolean state)
• JCheckBox(String s, Icon i)
• JCheckBox(String s, Icon i, boolean state)
• The state of the check box can be changed via the
following method:
void setSelected(boolean state)
• When a check box is selected or deselected, an item
event is generated. This is handled by
itemStateChanged( ).
Inside itemStateChanged( ), the getItem( )
method gets the JCheckBox object that generated
the event.
• The getText( ) method gets the text for that check
box.
JRadioButton
• Radio buttons are supported by the JRadioButton class,
which is a concrete implementation of AbstractButton. Its
immediate super-class is JToggleButton, which provides
support for two-state buttons.
• Some of its constructors are shown here:
• JRadioButton(Icon i)
• JRadioButton(Icon i, boolean state)
• JRadioButton(String s)
• JRadioButton(String s, boolean state)
• JRadioButton(String s, Icon i)
• JRadioButton(String s, Icon i, boolean state)
• Radio buttons must be configured into a group.
Only one of the buttons in that group can be
selected at any time.
• The ButtonGroup class is instantiated to create a
button group. Its default constructor is invoked
for this purpose.
• Elements are then added to the button group via
the following method:
• void add(AbstractButton ab)
JSeparator
A JSeparator is a horizontal or vertical line that separates components in a GUI,
like a divider or a ruler, to organize and visually distinguish different parts of
the interface.
Inherits JComponent class and supported by JSeparator class.

CONSTRUCTORS
JSeparator()
JSeparator(int orientation) // vertical or horizontal

METHODS
setOrientation(int orientation)
getOrientation()
addSeparator()
Advanced Swing
Components
Tabbed Panes
• A tabbed pane is a component that appears as a group of folders
(here, Tabs) in a file cabinet.
• Each tab has a title.
• When a user selects a tab, its contents become visible.
• Only one of the tabs may be selected at a time.
• Tabbed panes are commonly used for setting configuration
options.
• Tabbed panes are encapsulated by the JTabbedPane class, which
extends JComponent.
JTabbedPane
There are three constructors of JTabbedPane.
• JTabbedPane()
• JTabbedPane(int tabPlacement)

• The first form creates an empty TabbedPane with a


default tab placement of JTabbedPane -TOP.
• Second form creates an empty TabbedPane with the
specified tab placement :
JTabbedPane.TOP: Places the tabs at the top of the tabbed pane.
JTabbedPane.BOTTOM: Places the tabs at the bottom of the tabbed pane.
JTabbedPane.LEFT: Places the tabs at the left side of the tabbed pane.
JTabbedPane.RIGHT: Places the tabs at the right side of the tabbed pane.
JTabbedPane
• JTabbedPane(int tabPlacement, int tabLayoutPolicy)

• Tab layout policy may be either of the following:


JTabbedPane.WRAP_TAB_LAYOUT: A tab layout policy that wraps
tabs to the next line when there are too many tabs to fit in a single row.

JTabbedPane.SCROLL_TAB_LAYOUT: A tab layout policy that


provides a scrollable tab strip when there are too many tabs to fit in a
single row.
• Tabs are defined and added to TabbedPane via
the following method:
• void addTab(String str, Component comp)
• Here, str is the title for the tab, and
• comp is the component that should be added to
the tab (typically, a JPanel or a subclass of it)
Procedure to use a tabbed pane

1. Create a JTabbedPane object: JTabbedPane tabbedPane = new


JTabbedPane();
2. Call addTab( ) to add a tab to the pane:
● tabbedPane.addTab("Tab 1", new JPanel());
● "Tab 1" is the title of the tab
● new JPanel() is the component it contains
3. Repeat step 2 for each tab: tabbedPane.addTab("Tab 2", new JPanel());
tabbedPane.addTab("Tab 3", new JPanel());
4. Add as many tabs as needed, each with its own title and component
5. Add the tabbed pane to the content pane of the applet:
getContentPane().add(tabbedPane);
● getContentPane() gets the content pane of the applet
● add(tabbedPane) adds the tabbed pane to the content pane
class LangPanel extends JPanel
{
public LangPanel()
{
JButton b1 = new JButton("Marathi");
add(b1);
JButton b2 = new JButton("Hindi");
add(b2);
JButton b3 = new JButton("Bengali");
add(b3);
JButton b4 = new JButton("Tamil");
add(b4);
}
}
class ColorsPanel extends JPanel
{
public ColorsPanel()
{
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}
class FlavorsPanel extends JPanel
{
public FlavorsPanel()
{
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
import javax.swing.*;
/*<applet code="JTabbedPaneDemo" width=400
height=100> </applet> */
public class JTabbedPaneDemo extends Japplet {
public void init() {
JTabbedPane t = new JTabbedPane();
t.addTab("Languages", new LangPanel());
t.addTab("Colors", new ColorsPanel());
t.addTab("Flavors", new FlavorsPanel());
getContentPane().add(t);
}
}
Scroll Panes
• A scroll pane is a component that presents a rectangular
area in which a component may be viewed.
• Horizontal and/or vertical scroll bars may be provided
if necessary.
• Scroll panes are implemented in Swing by the
JScrollPane class, which extends JComponent.
• Here are the steps that you should follow to use a
scroll pane in an applet:
1.Create a JComponent object.
2.Create a JScrollPane object. (The arguments to
the constructor specify the component and the
policies for vertical and horizontal scroll bars.)
3.Add the scroll pane to the content pane of the
applet.
Constructors
• JScrollPane()
• JScrollPane(Component comp)
• JScrollPane(int vsb, int hsb)
• JScrollPane(Component comp, int vsb, int hsb)
• Here, comp is component to add to the scroll pane.
• vsb and hsb are int constants that define when vertical and horizontal scroll bars for this scroll
pane are shown. They are defined by the ScrollPaneConstants interface
(ScrollPaneConstants is an interface in Java that defines a set of constants used to control
the behavior of a JScrollPane.)

• HORIZONTAL_SCROLLBAR_ALWAYS: Always display a horizontal scrollbar, even if the


component is not larger than the viewport.
• HORIZONTAL_SCROLLBAR_AS_NEEDED: Display a horizontal scrollbar only when the
component is larger than the viewport.
• VERTICAL_SCROLLBAR_ALWAYS: Always display a vertical scrollbar, even if the
component is not larger than the viewport.
• VERTICAL_SCROLLBAR_AS_NEEDED: Display a vertical scrollbar only when the
component is larger than the viewport.
WITHOUT CONTENT PANE

public class JScrollPaneDemo extends Japplet {


public void init(){
setLayout(new BorderLayout());
JPanel jp = new JPanel();

//Grid layout code for printing 400 buttons------------------------------------------------------------


jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
jp.add(new JButton("Button " + b));
++b; } }
//—----------------------------------------------------------------------------------------------------------------------

int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(jp, v, h);
add(jsp, BorderLayout.CENTER);
}}
public class JScrollPaneDemo extends Japplet {
public void init(){
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
jp.add(new JButton("Button " + b));
++b; } }
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(jp, v, h);
contentPane.add(jsp, BorderLayout.CENTER);
}}
Trees
• A tree is a component that presents a hierarchical view of data.
• A user has the ability to expand or collapse individual sub-trees in this
display.

• TreeNode is typically a class.


• In Java, TreeNode is a class that represents a node in a tree-like data
structure.
JTree
• JTree(Hashtable ht): Creates a JTree from a Hashtable where each key-value pair represents
a node and its children.
• JTree(Object obj[]): Creates a JTree from an array of objects, where each object represents a
node in the tree.
• JTree(TreeNode tn): Creates a JTree from a TreeNode object, which represents the root node
of the tree.
• JTree(Vector v): Creates a JTree from a Vector of objects, where each object represents a
node in the tree.

EXAMPLES:-
1. JTree(Hashtable ht): JTree tree = new JTree(new Hashtable<String, String>()
{{ put("Root", "Child1"); }}); // key=”root”, value=”child1”, here root has 1 child
2. JTree(Object obj[]): JTree tree = new JTree(new Object[] {"Root", "Child1", "Child2",
"Grandchild1"}); // array of all nodes
3. JTree(TreeNode tn): JTree tree = new JTree(new DefaultMutableTreeNode("Root")); // put
in the root node (starting node)

4. JTree(Vector v): JTree tree = new JTree(new Vector<Object>() {{ add("Root");


add("Child1"); add("Child2"); }}); // vector of all nodes
Tree Path class
The TreePath class encapsulates (contains) information about a path
to a particular node in a tree.
It has the following methods:-
1.TreePath getPathForLocation(int x, int y)
The getPathForLocation( ) method is used to translate a mouse click on a specific
point of the tree to a tree path.
The return value is a TreePath object (It provides several constructors and methods.)
Here, x and y are the coordinates at which the mouse is clicked.
In a file folder structure. getPathForLocation(int x, int y) is like finding the path to a
specific file (e.g. "Documents/Pictures/Vacation.jpg" is the path when you click on
Vacation.png in the Pictures folder
2. The getPath( ) method of this class returns a TreePath object that describes
the path to the changed node.
Eg, If the changed node is a file called "example.txt" inside a folder called
"Documents" on the "C:" drive, then the TreePath object would represent the path:
"C:\Documents\example.txt".
TreeNode Interface

• The TreeNode interface declares methods that obtain


information about a tree node.

Eg, You can get a reference to the "parent" of a specific node (e.g. the
folder that contains the file). You can get a list of the "children" of a specific
node (e.g. the files and subfolders inside a folder).

(Continued on the Next page)


1. MutableTreeNode Interface:
- The `MutableTreeNode` interface extends the `TreeNode` interface.
- It adds methods that allow for modification of the tree, such as inserting and
removing child nodes or changing the parent node.

2. DefaultMutableTreeNode Class:
- `DefaultMutableTreeNode` implements the `MutableTreeNode` interface.
- It represents a node in a tree and can contain any object.
- Initially, this new tree node has no parent and no children.
- Eg. DefaultMutableTreeNode root= new DefaultMutableTreeNode("Options");
- The constructor `DefaultMutableTreeNode(Object obj)` creates a tree node that
contains the specified object (`obj`).

3. Creating a Hierarchy:
- To build a hierarchy of nodes, you can use the `add(MutableTreeNode child)`
method of `DefaultMutableTreeNode`.
- This method adds the specified child node to the current node, making it part
of the tree's structure.
TreeExpansion Listener Interface
• A JTree object generates events when a node is expanded or collapsed.

• The following methods allow listeners to register and unregister for


these notifications.
void addTreeExpansionListener(TreeExpansionListener tel)
void removeTreeExpansionListener(TreeExpansionListener tel)
Here, tel is the listener object.

• The TreeExpansionListener interface provides the following two methods:


void treeCollapsed(TreeExpansionEvent tee) - this method is called when
a subtree is hidden
void treeExpanded(TreeExpansionEvent tee) - subtress becomes visible
Here, tee is the tree expansion event.

(Tree expansion events are described by the class TreeExpansionEvent in the


javax.swing.event package. )
TreeSelectionListener
A TreeSelectionEvent is triggered when a user selects or deselects a node
in a tree, allowing the program to respond to changes in the tree's selection.

ValueChanged() is an event (e) that occurs when the selected value of a


component, such as a tree, list, or combo box, changes.

A TreeSelectionListener is an interface that listens for changes


in the selection of a tree.
The ValueChanged event is one of the events it listens for, when
the node in the tree changes.
Steps to use a tree in an Applet

1.Create a JTree object.


2.Create a JScrollPane object. (The arguments to the
constructor specify the tree and the policies for
vertical and horizontal scroll bars.)
3.Add the tree to the scroll pane.
4.Add the scroll pane to the content pane of the
applet.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
/* <applet code="JTreeEvents" width=400 height=200>
</applet>
*/
public class JTreeEvents extends JApplet
{
JTree tree;// Create a JTree object
JTextField jtf;// Create a JTextField object
public void init() {
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());

// Create the root node of the tree


DefaultMutableTreeNode root= new DefaultMutableTreeNode("Options");

// Create child nodes of the root node


DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
root.add(a); // Add node A to the root node
// Create another child node of the root node
DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
root.add(b); // Add node B to the root node

// Create child nodes of node A


DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
a.add(a1); // Add node A1 to node A
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
a.add(a2); // Add node A2 to node A
// Create child nodes of node B
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
b.add(b1); // Add node B1 to node B
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
b.add(b2); // Add node B2 to node B
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
b.add(b3); // Add node B3 to node B

// Create a JTree object with the root node


tree = new JTree(root);

// Create a JScrollPane to hold the JTree


int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(tree, v, h);

// Add the JScrollPane to the center of the content pane


contentPane.add(jsp, BorderLayout.CENTER);
tree.addMouseListener(this); // Use this class as the mouse listener
Tables
• A table is a component that displays rows and columns of
data.
• We can drag the cursor on column boundaries to resize
columns.
• We can also drag a column to a new position.
• Tables are implemented by the JTable class, which extends
JComponent. One of its constructors is shown here:
• JTable(Object data[ ][ ], Object colHeads[ ])
• JTable(int numRows, int numColumns)
• JTable(Vector rowData, Vector columnData)- you can think
of vectors as dynamic arrays
Java relies on three models to function:

1. TableModel: This model is responsible for managing the data that is displayed in the
table. It is defined by the TableModel interface and provides methods for accessing and
modifying the data.

2. TableColumnModel: This model is responsible for managing the columns of the table,
including their order, width, and visibility. TableColumnModel is defined by the
TableColumnModel interface.

3. ListSelectionModel: This model is responsible for managing the selection of rows in


the table. It provides methods for selecting and deselecting rows, as well as for getting
the currently selected rows. ListSelectionModel is defined by the ListSelectionModel
interface.

These three models work together to provide the functionality of a JTable.

The interfaces are part of the Java Swing API.


• the steps for using a table in an applet:
1) Create a JTable object.
2) Create a JScrollPane object. (The arguments to
the constructor specify the table and the policies
for vertical and horizontal scroll bars.)
3) Add the table to the scroll pane. (As table size
may be more than frame size)
4) Add the scroll pane to the content pane of the
applet.
import java.awt.*;
import javax.swing.*;

/* <applet code="JTableDemo" width=400 height=200>

</applet> */

public class JTableDemo extends JApplet {

public void init() {

Container contentPane = getContentPane();

contentPane.setLayout(new BorderLayout());

final String[] colHeads = { "Name", "Phone", "Fax" };//column headings (labels)


final Object[][] data = // records (row info)
{{ "Pramod", "4567", "8675" },

{ "Tausif", "7566", "5555" },

{ "Nitin", "5634", "5887" },

{ "Amol", "7345", "9222" },

{ "Vijai", "1237", "3333" },

{ "Ranie", "5656", "3144" },

{ "Mangesh", "5672", "2176" },

};

JTable table = new JTable(data, colHeads);// adding data rows (records) and column headings (labels)

int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;

int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

JScrollPane jsp = new JScrollPane(table, v, h);// adding table to scrollpane

contentPane.add(jsp, BorderLayout.CENTER); }}
JProgressBar
• JProgressBar visually displays the progress of some specified
task.
• JProgressBar shows the percentage of completion of
specified task.
• The progress bar fills up as the task reaches it completion.
• In addition to show the percentage of completion of task,
it can also display some text .
• Constructors of JProgressBar :
• JProgressBar() : creates an progress bar with no text on
it
• JProgressBar(int orientation) - orientation can be
SwingConstants.VERTICAL or
SwingConstants.HORIZONTAL
• JProgressBar(int min, int max) -
min: The minimum value of the progress bar. This is the starting point of the
progress bar, usually 0.
max: The maximum value of the progress bar. This is the end point of the
progress bar, usually 100.

• JProgressBar(int orientation, int min, int max)


Methods of JProgressBar are :

• void setMaximum(int n) : sets the progress bar’s maximum value to the value n.
• void setMinimum(int n) : sets the progress bar’s minimum value to the value n.
• int getMaximum() : returns the progress bar’s maximum value.
• int getMinimum() : returns the progress bar’s minimum value.
• String getString() : get the progress bar’s current value.
• void setString(String s) : set the value of the progressBAR to the String s but does
not display it.
• void setValue(int n) : set Progress bar’s current value to the value n.
• getValue(): Returns the current value of the progress bar.
• setStringPainted(boolean b): Sets whether the progress bar should paint (display)
the string or not.
• setOrientation(int o): Sets the orientation of the progress bar (either horizontal or
vertical).
• getOrientation(): Returns the orientation of the progress bar.
• addChangeListener is used to react to changes in the progress bar's value
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Test extends JFrame {


private JProgressBar progressBar;
private JButton startButton;
public Test() {
// Set up the frame
setTitle("Basic JProgressBar Example");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);

// Create and set up the progress bar


progressBar = new JProgressBar(0, 100); // Min value: 0, Max value: 100
progressBar.setValue(0);
progressBar.setStringPainted(true); // Show percentage text on the progress bar
// Create and set up the button
startButton = new JButton("Start Progress");
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Start a simple progress increment when the button is clicked
for (int i = 0; i <= 100; i += 10) {
try {
Thread.sleep(500); // Wait for half a second
} catch (InterruptedException ex) {
ex.printStackTrace();
}
progressBar.setValue(i); // Update progress bar value
} }
});
// Add components to the frame
add(progressBar);
add(startButton);

// Make the frame visible


setVisible(true);
}
public static void main(String[] args) {
new Test());
}}
JPasswordField
Allows user to input text in the form of password
characters.
Inherits JTextField class.

CONSTRUCTORS:
JPasswordField()
JPasswordField(int columns)- maximum number of
characters allowed
JPasswordField(String text) - text is not placeholder
value, it is default text that appears in the password field
JPasswordField(String text, int columns)

You might also like