0% found this document useful (0 votes)
53 views137 pages

Ajp 2 Swings

The document discusses Swing components and concepts. It provides an introduction to Swing and compares it to AWT. Key Swing components discussed include JFrame, JApplet, and others. It describes features of Swing like borders, tooltips, scrolling, pluggable look and feel, and new layout managers. The advantages of Swing include lightweight components, MVC architecture, and additional functionality over AWT.

Uploaded by

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

Ajp 2 Swings

The document discusses Swing components and concepts. It provides an introduction to Swing and compares it to AWT. Key Swing components discussed include JFrame, JApplet, and others. It describes features of Swing like borders, tooltips, scrolling, pluggable look and feel, and new layout managers. The advantages of Swing include lightweight components, MVC architecture, and additional functionality over AWT.

Uploaded by

Ganesh Ekambe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 137

UNIT 2

SWINGS

Prof. Abhijeet Sir


10 marks

By: Abhijeet Sir


Computer Department
GTMC NANDED
 2.1 Introduction to Swing:
 Swing Features, Difference between AWT and
Swing.
 2.2 Swing Components: JApplet, Icons and
Labels, Text Fields, Combo Boxes.

Prof. Abhijeet Sir


 2.3 Buttons: The JButton, Check Boxes, Radio
Buttons.
 2.4 Advanced Swing Components: Tabbed Panes,
Scroll Panes, Trees, Tables, Progressbar,
Tooltips.
 2.5 MVC Architecture.
 Introduction

 Swing is a set of classes this provides more


powerful and flexible components than are
possible with the AWT.

Prof. Abhijeet Sir


 In addition to the familiar components,
such as buttons, check boxes, and labels,
Swing supplies several exciting additions,
including tabbed panes, scroll panes, trees,
and tables.
 Evenfamiliar components such as buttons
have more capabilities in Swing.

Prof. Abhijeet Sir


 Forexample, a button may have both an
image and a text string associated with it.
 Also, the image can be changed as the
state of the button changes
Prof. Abhijeet Sir
Class Description
AbstractButton Abstract super-class for Swing buttons.

Prof. Abhijeet Sir


ButtonGroup Encapsulates a mutually exclusive set of buttons.
ImageIcon Encapsulates an icon.
JApplet The Swing version of Applet.
JButton The Swing push button class.
JCheckBox The Swing check box class.
JComboBox Encapsulates a combo box (a combination of a drop-
down list and text field).
JLabel The Swing version of a label.

Prof. Abhijeet Sir


JRadioButton The Swing version of a radio button.
JScrollPane Encapsulates a scrollable window.
JTabbedPane Encapsulates a tabbed window.
JTable Encapsulates a table-based control.
JTextField The Swing version of a text field.
JTree Encapsulates a tree-based control
The Swing-related classes are contained in javax.swing and its
subpackages, such as javax.swing.tree.

Object java.lang

Component

Prof. Abhijeet Sir


Container

JComponent
Window

Frame JApplet JPanel JFrame

JFrame

The Swing family tree (Ref. No. 2)


 Swing Features (Ref. No. 2)

 Besides the large array of components in Swing


and the fact that they are lightweight, Swing
introduces many other innovations.

Prof. Abhijeet Sir


 Borders
 We can draw borders in many different styles
around components using the setborder( )
method.

 Graphics Debugging

 We can use set Debugging Graphics Options


method to set up graphics debugging which means
among the other things, that you can watch each
line as its drawn and make it flash.

Prof. Abhijeet Sir


 Easy mouseless operation
 It is easy to connect keystrokes to components.
 Tooltips
 We can use the setToolTip Text 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.

Prof. Abhijeet Sir


 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).

Prof. Abhijeet Sir


 New Layout Managers
 Swing introduces the BoxLayout and
OverlayLayout layout managers.
 One of the differences between the AWT and Swing
is that, when we redraw items on the screen of
AWT, the update method is called first to redraw
the item‟s background and programmers often
override update method to just call the paint
method directly to avoid flickering.

Prof. Abhijeet Sir


 In Swing, on the other hand the update method
does not redraw the item‟s background because
components can be transparent; instead update
just calls paint method directly.
 Advantages and
Disadvantages of Swing
Advantages:
 1. Swing provides paint debugging support for
when you build your own component.

Prof. Abhijeet Sir


 2. Swing components are lightweight than AWT.

 3. Swing components follow the Model-View-


Controller (MVC) paradigm and thus can provide a
much more flexible UL
 4. Swing provides both additional components
like JTable, JTree etc and added functionality to
replacement of AWT components.

Prof. Abhijeet Sir


 5. Swing provides built-in double buffering.
 Disadvantages:

 1. It can be slower than AWT (all components are


drawn), when you are not careful about
programming.

Prof. Abhijeet Sir


 2. Swing components might not behave exactly
like native components which look like native
components.

 3. It requires Java 2 or a separate JAR file


DIFFERENCE BETWEEN AWT AND SWING

Prof. Abhijeet Sir


Prof. Abhijeet Sir
 SWING COMPONENTS
 Swing components are not implemented by
platform specific code. Instead they are written
entirely in Java and therefore, are platform
independent. All Swing components name start
with letter J.

Prof. Abhijeet Sir


 Swing component is called light weight, as it does
not depend on any non-java system classes. Swing
components have their own view supported by
java·s look and feel classes.
 Swing components have pluggable look and feel so
that with a single set of components you can
achieve the same look and feel on any operating
system platform.
 JFrame
 The frame is a top-level container or window, on
which other Swing components are placed.
 A JFrame component is used to create windows
in a Swing program.

Prof. Abhijeet Sir


 It extends java.awt.Frame class.

 Every JFrame object has a root pane.


 Constructors of Jframe Class:
 1. JFrame()

 This constructor creates a new frame without


title.

Prof. Abhijeet Sir


 2. JFrame(String title)
 This constructor constructs the new frame with
title.
Methods of Jframe Class:
1. Container getcontentPane()
This method returns, a Content Pane for the
Jframe.
2. void setLayout(LayoutManager)

Prof. Abhijeet Sir


This method sets the LayoutManager for the
JFrame.
3. void setJMenuBar(JMenuBar)
This method sets the JMenu Bar to the JFrame.
4. Void setlconlmage(Image image) Prints icon
image on JFrame.
There are two way to create a JFrame Window:
 1. By instantiating JFrame class.

Prof. Abhijeet Sir


 2. By extending JFrame class.
. By instantiating JFrame class.

import javax.swing.*;
import java.awt.*;
public class JFrameDemo
{

Prof. Abhijeet Sir


JFrame f1;
JFrameDemo()
{
f1 = new JFrame("MyWindow");
JButton btn = new JButton("Say
Hello");
f1.add(btn);
f1.setlayout(new FlowLayout());
f1.setDefaultCloseOperation(JFrame.E
XIT_ON_CLOSE};

Prof. Abhijeet Sir


f1.setSize(400, 400);
f1.setVisible(true);
}
public static void main(String[]args)
{

Prof. Abhijeet Sir


new JFrameDemo();
}
}
Prof. Abhijeet Sir
OUTPUT
 Program 2.2: Creating ]
Frame window by extending JFrame class.
import javax.swing.•;
import java.awt.*;
public class JFrameDemo1 extends JFrame
{

Prof. Abhijeet Sir


JFrame jf;
JFrameDemo1()
{
setTitle("MyWindow");
JLabel lb = new JLabel("Welcome");
add(lb);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
public static void main(String[] args)

Prof. Abhijeet Sir


{
new JFrameDemo1() ;
}
}
JAPPLET
 JApplet is a class that represents the Swing
applet.

Prof. Abhijeet Sir


 It is a subclass of Applet class and must be
extended by all the applets that use Swing.
 It provides all the functionalities of the AWT
applet as well as support for menubars and
layering of components.
 Whenever we require to add a component to it,
the component is added to the content pane.
 Applet supports various panes such as root pane
glass pane and content pane. .
 Root Pane: Swing containers like JApplet,
JFrame, JWindow and JDialog delegate their
duties to the root pane represented by the class

Prof. Abhijeet Sir


JRootPane. • The root pane is made up of a
content pane, layered pane, glass pane and an
optional menu bar, other GUI components must
be added to one of Frame Content Pane Content
Pane Layered Pane these roots pane members,
rather than to the root pane itself.
 2. Content Pane: • This pane is actually sits on
one of the layers of a specially layered pane. •
The layered pane in Fig. 2.4 contains several

Prof. Abhijeet Sir


layers meant for displaying different Swing
components, depending on the GUI's
requirements.
 Fig. 2.4 shows the position of the content pane in
the specially layered pane. The menu bar and the
content pane sit on the Frame-Content-Layer.
 3. Glass Pane: It is a member of the multi-layered,
root pane. It is used to draw over an area that
already contains some components.
 • The content pane makes Swing applets different
from regular applets in the following ways:

Prof. Abhijeet Sir


 Components are added to the content pane of Swing
applets, not directly to the applets.
 The layout manager is set for the content pane of a
Swing Applet, not directly for the applet.
 The default layout manager for the content pane of
a Swing based applet is BorderLayout.
 This differs from the default Layout Manager for
Applet which is Flow Layout.
: PROGRAM TO DEMONSTRATE GLASS
PANE.
import javax.swing.*;
import java .awt.*;
/*

Prof. Abhijeet Sir


<applet code =“JAppletDemo” width=250 heigth=150>
*/

public class JAppletDemo extends JApplet


{
public void paint(Graphics g)
{
g . drawstring( "Welcome", 100,100);
}
}
Program 2.3:
Program to demonstrate glass pane.
import javax.swing.*;
import java.awt.*; /*

<applet code="JAppletDemo" width=250 height=150>

Prof. Abhijeet Sir


</applet> */
public class JAppletDemo extends Applet
{
public void paint(Graphics g)
{
g. drawstring( "Welcome", 100,100);
}

}
Prof. Abhijeet Sir
 JLabel

Prof. Abhijeet Sir


 One of the simplest Swing component is JLabel.
A JLabel object is a component for placing text in
a container. •
 This class is used to create single line read only
text which describes the other component. Labels
can display text as well as Images.
 Constructors of Label Class:

1. JLabel()
Create a empty label having no text and icon
 2. Jlabel(String str)

Create a label having some text.

Prof. Abhijeet Sir


 3. JLabel(Imageicon i)
Creates a label having icon image.
import java.awt.Dimension;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class JLabelDemo extends JFrame

Prof. Abhijeet Sir


{
private JLabel jb1 = new JLabel();
private JLabel jb2 =new JLabel();
public JLabelDemo()
{
setlayout( null );
setSize( new Dimension(400, 300) );
jb1.setText( "UserName");

Prof. Abhijeet Sir


jb1.setBounds(new Rectangle(40, 55, 80, 25));
jb2.setText( "Password");
jb2.setBounds(new Rectangle(40, 95, 60, 25));
add(jb1, null);
add(jb2, null);
}
public static void main(String args[]) {
JFrameDemo frame=new J FrameDemo();
frame.setVisible(true);
}
Prof. Abhijeet Sir
 Icons
 Many Swing components, such as labels, buttons,
and tabbed panes, can be decorated with an icon - a
fixed-sized picture.
 An icon is an object that adheres to the Icon

Prof. Abhijeet Sir


interface.
 Swing provides a Imageicon class which
implements the Icon interface which paints an icon
from a GIF, JPEG, or PNG image.
Prof. Abhijeet Sir
1)ImageIcon(String filename)

2) ImageIcon(URL url)

The first form uses the image in the file named

Prof. Abhijeet Sir



filename. The second form uses the image in the
resource identified by url. The ImageIcon class
implements the Icon interface that declares the
methods shown here:
Method Description
int getIconHeight( ) Returns the height of the

Prof. Abhijeet Sir


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
import java.awt.*;
import javax.swing.*;
/* <applet code="JLabelDemo" width=250
height=150> </applet> */
public class JLabelDemo extends JApplet
{

Prof. Abhijeet Sir


public void init()
{
Container contentPane = getContentPane();
ImageIcon ii = new ImageIcon("IC.jpg");
JLabel jl = new JLabel("IC", ii, JLabel.CENTER);
contentPane.add(jl);
}
}
Prof. Abhijeet Sir
 Text Fields

 The Swing text field is encapsulated by the


JTextComponent class, which extends
JComponent.

Prof. Abhijeet Sir


 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)

 JTextField(String s, int cols)

 JTextField(String s)

Prof. Abhijeet Sir


 Here, s is the string to be presented, and cols is
the number of columns in the text field.
 The following example illustrates how to create a
text field.
 The applet begins by getting its content pane, and
then a flow layout is assigned as its layout
manager.
 Next, a JTextField object is created and is added
to the content pane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet

Prof. Abhijeet Sir


{
JTextField jtf; public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
jtf = new JTextField(15);
contentPane.add(jtf);
}
}
Prof. Abhijeet Sir
 JTextArea :
 The JTextArea is used to accept several lines of
text from the user and it has capabilities not
found in the A WT class. .

Prof. Abhijeet Sir


 JTextArea class itself does not handle scrolling
but implements the Scrollable interface which
allows it to be placed inside a JScrollPane and
thus implement scrolling.
 A JTextArea can be created using one of the
following constructors:
 1. JTextArea( ):

Constructs a new TextArea.

Prof. Abhijeet Sir


 2. JTextArea(int rows, int columns):
Constructs a new empty TextArea with the specified
number of rows and columns.
 3. JTextArea(String text): Constructs a
newTextArea with the specified text displayed.

 4. JTextArea(String text, int rows, int columns):


Constructs a new TextArea with the specified text

Prof. Abhijeet Sir


and number of rows and columns.
PROGRAM TO DEMONSTRATE JTEXTAREA
import javax.swing.*;
import java.awt.*;
public class JFrameDemo extends JFrame
{

Prof. Abhijeet Sir


public JFrameDemo()
{
setLayout(new FlowLayout());
JLabel jll = new JLabel ("TextArea");
add(jll);
JTextArea tal = new JTextArea(10,20);
add(tal ) ;
setSize(600, 600);
setVisible(true);
}
public static void main(String args[])
{
new JFrameDemo();
}
}
}
Prof. Abhijeet Sir
 JComboBox
 Swing provides a combo box (a combination of a
text field and a dropdown list) through the
JComboBox class, which extends JComponent.
 A combobox normally displays one entry.

Prof. Abhijeet Sir


 However, it can also display a drop-down list that
allows a user to select a different entry. We can
also type our selection in to the text field.
 The JComboBox component, similar to Choice
component in A WT.
 JComboBox's constructors are shown below:
 1. JComboBox () :

This constructor creates an empty JComboBox


instance.

Prof. Abhijeet Sir


2. JComboBox(Object[ ] items):
Creates a JComboBox that contains the elements of
the specified array.
 import javax.swing.*;
public class JFrameDemo extends JFrame
{
public JFrameDemo()
{
String country[] = {"India", "Aus", "U.S.A", "England",
"Newzeland"};
JComboBox cb = new JComboBox(country);

Prof. Abhijeet Sir


cb.setBounds(50, 50, 90, 20);
add(cb);
setLayout(null);
setSize(400, 500);
setVisible(true);
}
public static void main(String args[])
{
new JFrameDemo();
}
}
Prof. Abhijeet Sir
 JButton •

 This class is used to create a push buttons.

Prof. Abhijeet Sir


 This class is subclass of Abstract Button class.
Prof. Abhijeet Sir
Prof. Abhijeet Sir
import javax.swing.*;
public class JFrameDemo extends JFrame
{
public JFrameDemo()
{
setLayout(null);
setSize(400, 500);

Prof. Abhijeet Sir


setVisible(true);
JButton jb = new JButton("Cancel");
jb.setBounds(50, 50, 90, 20);
add(jb);
}

public static void main(String args[])


{
new JFrameDemo();
}
}
Prof. Abhijeet Sir
 JRadioButton
This class is used to create radio button with a text
or icon.
Radio buttons are supported by the JRadioButton
class, which is a concrete implementation of

Prof. Abhijeet Sir


AbstractButton..

Once, a radio button is created they must be kept in


one group, which is created by using the
ButtonGroup class Radio buttons must be configured
into a group.

In JRadioButton only one of the buttons in that


group can be selected at any time.
 Constructors of JRadioButton:

 1. JRadioButton(): Create a empty radio button


having no title and icon.

2. JRadioButton(String l): Create a radio button

Prof. Abhijeet Sir



having label.

 3. JRadioButton(Icon i): Creates a radio button


having icon image.
 4. JRadioButton(String 1, Icon i): Creates a radio
button having string label and icon image.

 5. JRadioButton(String 1, Icon i, boolean sel ected):


Creates a radio button having string label and icon
image and default selected if true is passed.

Prof. Abhijeet Sir


 6. JRadioButton(String 1, boolean selected):
Creates a radio button having string label and
option for default selected policy.
import javax.swing.*;
import java.awt.*;
public class JFrameDemo extends JFrame
{

public JFrameDemo()
{
setLayout(new FlowLayout());
setSize(400,500);

Prof. Abhijeet Sir


setVisible(true);
JRadioButton jrl =new JRadioButton("Java",true);
add(jrl);
JRadioButton jr2 =new JRadioButton("C++");
add(jr2);
}
public static void main(String args[] )
{
new JFrameDemo();
}

}
Prof. Abhijeet Sir
JCHECKBOX
 A checkbox is a control that may be turned ON or
OFF by the user to indicate some option.
 Swing

 • The class JCheckBox is an implementation of a

Prof. Abhijeet Sir


check box - an item that can be selected or
deselected, and which displays its state to the user.
 The JCheckBox class is used to create CheckBox in
Swing.
 CheckBox has the following constructors:

 1. JCheckBox(): Creates an initially unselected


check box button with no text, no icon.

Prof. Abhijeet Sir


 2. JCheckBox ( Icon icon): Creates an initially
unselected check box with an icon.

 3. JCheckBox(I con icon, boolean selected): Creates


a check box with an icon and specifies whether or
not it is initially selected.
 4. JCheckBox(String text): Creates an initially
unselected check box with text.

 5. JCheckBox(String text, boolean selected):


Creates a check box with text and specifies whether
or not it is initially selected.

Prof. Abhijeet Sir


 6. JCheckBox(String text, Icon icon): Creates an
initially unselected check box with the specified
text and icon.

 7. JCheckBox(String text, Icon icon, boolean


selected):
 Creates a check box with text and icon, and
specifies whether or not it is initially selected.
import javax.swing.*;
import java.awt.*;
public class JFrameDemo extends Jframe
{
public JFrameDemo()
{
setLayout( new Flowlayout());

Prof. Abhijeet Sir


set5ize(400, 500);
setVisible(true);
JCheckBox jrl = new JCheckBox("Java",true);
add(jrl);
JCheckBox jrZ = new JCheckBox("C++");
add(jrZ);
public static void main(String args[])
{
new JFrameDemo();
}
}
}
Prof. Abhijeet Sir
ADVANCED SWING COMPONENTS
 Swing provides several advanced components
such as tabbed panes, scroll panes, trees, tables,
progress bars and so on.

Prof. Abhijeet Sir


 This sections deals with this advanced
component in Swing.
Tabbed Panes (JTabbedPane)
 A tabbed pane is a component that appears as a
group of folders in a file cabinet.
 Each folder has a title. When a user selects a
folder, its contents become visible.

Prof. Abhijeet Sir


 Only one of the folders 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
 There are three constructors of
JTabbedPane:
 1. JTabbedPane(): Creates an empty.
TabbedPane with a default tab placement of
JTabbedPane TOP.

Prof. Abhijeet Sir


 2. JTabbedPane( int tabPlacement ):
 Creates an empty TabbedPane with the specified
tab placement of any of the following:
1)JTabbedPane.TOP
2)JTabbedPane.BOTTOM
3)JTabbedPane.LEFT
4)JTabbedPane.RIGHT
 3. JTabbedPane(int tabPlacement, int
tabLayoutPolicy)
: Creates an empty TabbedPane with the specified
tab placement and tab layout policy.

Prof. Abhijeet Sir


Tab placements are listed above.

Tab layout policy may be either of the


following:
1) JTabbedPane.WRAP_TAB_LAYOUT

2) JTabbedPane.SCROLL_TAB_LAYOUT
 Wrap Tabbed Policy

Prof. Abhijeet Sir


 Scroll Tab Policy

Prof. Abhijeet Sir


 Tabs are added via the following method:

void addTab(String str, Component comp)

 • Here, str is the title for the tab, and comp is the

Prof. Abhijeet Sir


component that should be added to the tab.
Typically, a JPanel or a subclass of it is added.
 The general procedure to use a tabbed pane in an
applet is outlined here:

 Step 1 Create a JTabbedPane object.


 Step 2 Call addTab() to add a tab to the pane.

Prof. Abhijeet Sir


 (The arguments to this method define the title of
the tab and the component it contains.)
 Step 3 Repeat step 2 for each tab.

 Step 4 Add the tabbed pane to applet/Frame.


import javax.swing.*;
/*
<applet code="JTabbedPaneDemo" width=400 height=100>
</applet>
*/
public class JTabbedPaneDemo extends JApplet

Prof. Abhijeet Sir


{
public void init()
{
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Languages“ new LangPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
getContentPane().add(jtp);
}
}
class LangPanel extends JPanel
{
public LangPanel()
{
JButton b1 = new JButton("Marathi");

Prof. Abhijeet Sir


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");

Prof. Abhijeet Sir


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();

Prof. Abhijeet Sir


jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
Prof. Abhijeet Sir
import javax.swing.*;
public class TabbedPaneExample
{
JFrame f;

Prof. Abhijeet Sir


TabbedPaneExample(){
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
f.add(tp);
f.setSize(400,400);

Prof. Abhijeet Sir


f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args)
{
new TabbedPaneExample();
}
 }
Prof. Abhijeet Sir
JSCROLLPANE
 A scroll pane is a component that presents a
rectangular area in which a component may be
viewed.

Prof. Abhijeet Sir


 Horizontal and/or vertical scroll bars may be
provided if necessary.
 Scroll panes are implemented in Swing by the
JScrollPane class.
Prof. Abhijeet Sir
 Some of its constructors are shown here:

 JScrollPane()
 JScrollPane(Component comp)

 JScrollPane(int vsb, int hsb)

Prof. Abhijeet Sir


 JScrollPane(Component comp, int vsb, int hsb)

 Here, comp is the component to be added to the


scroll pane.
 vsb and hsb are int constants that define when
vertical and horizontal scroll bars for this scroll
pane are shown. These constants are defined by
the ScrollPaneConstants interface.
Prof. Abhijeet Sir
 Here are the steps that you should follow to use a
scroll pane in an applet:

1)Create a JComponent object.

Prof. Abhijeet Sir


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.
import java.awt.*;
import javax.swing.*;
/* <applet code="JScrollPaneDemo" width=300 height=250>

Prof. Abhijeet Sir


</applet> */

public class JScroll PaneDemo extends Japplet


{
public void init()
{
setlayout(new Borderlayout());
JPanel jp = new )Panel ();
jp.setlayout(new Gridlayout(10, 10));
int b = 0;
for (inti = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
jp.add(new JButton("Button " + b));
++b;
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_
AS_NEEDED;

Prof. Abhijeet Sir


int h =ScrollPaneConstants.HORIZONTAL_SCRDLLBAR_
AS_NEEDED;
JScrollPane jsp = new JScrollPane(jp, v, h);
add(jsp, Borderlayout.CENTER);
}
}
Prof. Abhijeet Sir
 JTree

 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.

Prof. Abhijeet Sir


 Any computer user who had used Windows Explorer
or File Manager will recall seeing a tree-like
structure depicting files and folders.
 This tree-like structure will display folders and
subfolders like branches of a tree one below the
other.
Prof. Abhijeet Sir
 Similar, tree-like structures can be created in
Java using JTree.

 Trees are implemented in Swing by the JTree


class, which extends JComponent

Prof. Abhijeet Sir


Prof. Abhijeet Sir
Prof. Abhijeet Sir
import java.awt. *;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class JTreeDemo
{
JTree tree;

Prof. Abhijeet Sir


JFrame f;
JTreeDemo()
{
f=new Jframe();
f.setLayout(new BorderLayout());
// Create top node of tree
DefaultMutableTreeNode top = new
DefaultMutableTreeNode("Options");
DefaultMutableTreeNode a= new
DefaultMutableTreeNode("A");
top. add(a);

Prof. Abhijeet Sir


DefaultMutableTreeNode b= new
DefaultMutableTreeNode("B");
top.add(b);
// Create subtree of "A"
DefaultMutableTreeNode al= new
DefaultMutableTreeNode("Al");
a.add(al);
DefaultMutableTreeNode a2= new
DefaultMutableTreeNode("A2");

Prof. Abhijeet Sir


a.add(a2);
// Create subtree of "B"
DefaultMutableTreeNode bl= new
DefaultMutableTreeNode("B1");
b.add(bl);
DefaultMutableTreeNode b2 =new
DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3 =new
DefaultMutableTreeNode("B3");
b.add(b3);
tree = new JTree(top);
JScrollPane jsp = new JScrollPane(tree);
f.add(jsp, BorderLayout.CENTER);
f.setSize(500,500);
f.setVisible(true);

Prof. Abhijeet Sir


}
publ ic static void main(String args(])
{
JTreeDemo jl=new JTreeDemo();
}
}
Prof. Abhijeet Sir
 JTable
 • A table is a component that displays rows and
columns of data. JTable class use to create tables
for a GUI based application.
 We can drag the cursor on column boundaries to

Prof. Abhijeet Sir


resize columns. We can also drag a column to a new
position.
 • Tables are implemented by the JTable class,
which extends JComponent.
 JTable class defines following constructors:
 JTable (Object data( )( ) , Object col Heads( ))

 JTable(int numRows, int numColumns)

 JTable(Vector rowData, Vector columnData)

Prof. Abhijeet Sir


 Here, data is a two-dimensional array of the
information to be presented and colHeads is a
onedimensional array with the column headings.
 The 'numRows' and 'numColumns' are values with

which the table is to be created. The 'rowData' and


'columnData' are the vector values by which the
table is constructed
 Here, are the steps for using a table in an applet:
 Step 1 Create a JTable object.

 Step 2 Create a JScrollPane object (The

Prof. Abhijeet Sir


arguments to the constructor specify the table and
the policies for vertical and horizontal scroll bars).

 Step 3 Add the table to the scroll pane.

 Step 4 Add the scroll pane to the container


(applet/frame)
 The following program illustrates how to create
and use a table.
 • A one-dimensional array of strings is created for
the column headings. This table has three
columns.
 A two-dimensional array of strings is created for

Prof. Abhijeet Sir


the table cells. We can see that each element in the
array is an array of three strings.

These arrays are passed to the JTable constructor.


The table is added to a scroll pane and then the
scroll pane is added to the container
import j avax.swing.*;
public class JTableDemo
{
JFrame f;
JTableDemo()

Prof. Abhijeet Sir


{
f =new JFrame();
String rows[ ] [ ]={ { "101", "Amit", "670000"},
{"102", "Jai","780000"},
{"101" ,"Sachin","700000"}
};
String columns ( l ={"ID"' "NAME" ' "SALARY"};
JTable jt=new JTable(rows,columns);
jt .setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);

Prof. Abhijeet Sir


f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args)
{
new JTableDemo();
}

}
Prof. Abhijeet Sir
 JToolTip
 A tooltip is a textual pop-up that momentarily
appears when the mouse cursor rests inside the
Components painting region
 We can add tooltip text to almost all the
components of Java Swing by using the method

Prof. Abhijeet Sir


setToolTipText(String s).
 This method sets the tooltip of the component to
this specified strings.
 When the cursor enters the boundary of that
component a popup appears and text is
displayed.

 A JToolTip is a small pop-up window designed to


contain informative text about a component when

Prof. Abhijeet Sir


the mouse moves over it.

 In short, tooltip is a string has short description


and they are used to explain the functionality of
the component.
 Program for tooltip.
import javax.swing.•;

Prof. Abhijeet Sir


public class ToolTipExample
{
public static void main(String[] args)
{
JFrame f =new JFrame("Password Field
Example");
//Creating PasswordField and label
JPasswordField value = new JPasswordField();
value.setBounds(100,100,100,30);
value.setToolTipText("Enter your Password");
JLabel ll=new JLabel("Password:");

Prof. Abhijeet Sir


ll.setBounds(20,100, 80,30);
//Adding components to frame
f.add(value);
f.add( l l);
f.setSize(300,300);
f.setlayout(null);
f.setVisible(true);
}
}
Prof. Abhijeet Sir
 JProgressBar
 The JProgressBar class is used to display the
progress of the task. It inherits JComponent class.
 • JProgressBar visually displays the progress of
some specified task.

Prof. Abhijeet Sir


 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.
Prof. Abhijeet Sir
Prof. Abhijeet Sir
import javax.swing.*;
public class ProgressBarExample extends Jframe
{
JProgressBar jb;
int i =0,num=0;
ProgressBarExample( )

Prof. Abhijeet Sir


{
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue{0};
jb.setStringPainted(true);
add(jb);
setSize(250,150);
setlayout(null);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i =i+20;

Prof. Abhijeet Sir


try{
Thread.sleep(150);
}
Catch(Exception e)
{
}
}
}
public static void main(String[] args)
{

Prof. Abhijeet Sir


ProgressBarExample m=new
ProgressBarExample() ;
m.setVisible(true);
m. iterate();
}
}
Prof. Abhijeet Sir
 MVC Architecture
 Swing components follow the Model-View-
Controller (MVC) paradigm and thus can provide
a much more flexible UI.
 Swing uses MVC architecture as the fundamental

Prof. Abhijeet Sir


design behind each of its components.

 The MVC architectural pattern is used in software


engineering to allow for the separation of three
common features of GUI applications:
 The data access (typically via a database).
 The business logic (how the data will be used).

Prof. Abhijeet Sir


 User interaction (how the data and actions

will be visually presented).


Prof. Abhijeet Sir
 The components are:
 1. Model: This provides the means by which data
is retrieved and manipulated.

2. View: This represents the visual interface

Prof. Abhijeet Sir



components of the Graphical User Interface (GUI)
application which interact with the user. The
interaction is of an event-driven nature where
actions are initiated via keyboard and mouse.

 3. Controller: This joins the Model with the View


and is the heart of the control logic by associating
user-generated events with data actions.
 The interactions correspond to the Fig. 2.2 as follows:
 1. All actions begin in the view through events
generated by the user. The controller provides
listeners for the events.
The controller also has the ability to manipulate
the state of the view objects in a way which offers a

Prof. Abhijeet Sir


response to the events generated by the user.

 2. The controller interacts with the model by either


requesting information from the data source based on
user-generated events, or by modifying the data based
on these events.
 3. The model provides the programming interface
which the controller must use to access the
database, i.e., the controller does not interact directly
with the database.
In particular the notion of "connection" is never seen in
the controller. Furthermore, the model also provides

Prof. Abhijeet Sir


means to avoid, direct SQL queries to the database.
4. The view interacts with the model only to know
about type information and other data
abstractions held in the model. The relatively weak
link indicates that the View/Model
interaction should be "minimal" because the
manipulation of data is to be done within the event

Prof. Abhijeet Sir


handlers of the controller.
Prof. Abhijeet Sir
Prof. Abhijeet Sir

You might also like