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

AJP CHP 2

AJP 22517 chapter 2 notes

Uploaded by

arqamqazi549
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)
24 views

AJP CHP 2

AJP 22517 chapter 2 notes

Uploaded by

arqamqazi549
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
You are on page 1/ 72

Unit-II

SWING

1
Introduction to Swing
Swing API is set of extensible GUI Components to create
JAVA based Front End/ GUI Applications. It is build upon top
of AWT API and acts as replacement of AWT API as it
has almost every control corresponding to AWT controls.

2
Swing Features
 Light Weight - Swing component are independent of native
Operating System's API as Swing API controls are rendered
mostly using pure JAVA code instead of underlying operating
system calls.
 Rich controls - Swing provides a rich set of advanced
controls like Tree, TabbedPane, slider, colorpicker, table
controls
 Pluggable look-and-feel- SWING based GUI Application
look and feel can be changed at run time based on available
values.

3
Difference between AWT and
Swing
No. Java AWT Java Swing
1 AWT components are platform- Java swing components are
dependent. platform- independent.

2 AWT components are heavyweight. Swing components are lightweight.


3 AWT doesn't support pluggablelook Swing supports pluggable look and feel.
and feel.
4 AWT provides less components than Swing. Swing provides more powerful
componentssuch as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.

5 AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and
view.

4
Hierarchy of Java Swing
classes

5
Using Top-Level
Containers
Swing provides three generally useful top- container
level classes: JFrame, JDialog, and JApplet.

A container has several layers in it. You can think of a layer as


a transparent film that overlays the container.

In JavaSwing, the layer that is used to hold


objects is called the content pane.

 Objects are added to the content pane layer of the container.

The getContentPane() method retrieves the content pane


layer so that you can add an object to it.
6
Layers of Top Level
container
Each Top Level container defines a set of panes.
• Root Pane- extends Jcomponent and manages the appearance of
JFrame and Japplet objects.
• Glass Pane- Top level pane that covers all other panes. It is a
transparent instance of Jpanel class used to handle the mouse events
affecting the entire container.
• Layered Pane- instance of JLayeredPane class. It holds container
called the content pane and optional menu bar.
• Content Pane- used to hold all the visual components. It is an
opaque instance of Jpanel class and uses borderlayout.

7
Layers of Top Level
container

8
getContentPane() Method
Returns the contentPane object for this
container.
import java.awt.*;
import java.applet.*;
import javax.swing.*;
public class
GridLayoutExampl
e extends JApplet
{
public void
init()
{
Container c = getContentPane();
c.setLayout(new GridLayout(2,
4)); c.add(new JButton("One"));
c.add(new
JButton("Two"));
c.add(new
9 JButton("Three"));
c.add(new
Output of the Program

10
Another example of using Content
Pane
import java.awt.*;
import
javax.swing.*;
public class
Frame4a
{
public static void
main(String[] args)
{
JFrame f =
new
JFrame("JFram
e with a
JPanel");
JLabel L = new JLabel("Hello World !");
JPanel P = new JPanel(); / / Make a
Jpanel P.add(L);
f.getContentPane().add(P);
11
f.setSize(400,300);
JApplet
⚫ JApplet is a class that represents the Swing applet.

⚫ It is a subclass of Applet class.

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

12
⚫ Applet is a top-level container class and you should never
draw on it directly, instead you should draw on the
component class like JPanel and then add this JPanel to the
JApplet

⚫ The content pane can be obtained via the method shown


here: Container getContentPane( )
e.g. Container cp = getContentPane();

⚫ The add( ) method of Container can be used to add a


component to a content pane. Its form is shown here:
void add(comp)
e.g. add(cp);
13
Icons and
Labels
Icons
⚫ In Swing, icons are encapsulated by the ImageIcon
class, which paints an icon from an image.

Constructors:
⚫ ImageIcon(String filename)
⚫ ImageIcon(URL url)

14
Label
s labels are instances of the JLabel class, which
⚫ Swing
extends JComponent. It can display text and/or an icon.

Constructors:
⚫ JLabel(Icon i)
⚫ JLabel(String s)
⚫ JLabel(String s, Icon i, int align)

15
Methods used with
JLabel
The icon and text associated with the label can be read
and written by the following methods:

⚫ Icon getIcon( )

⚫ String getText( )

⚫ void setIcon(Icon i)

⚫ void setText(String s)

16
Example
:import java.awt.*;
import
javax.swing.*;
/* <applet
code="JLabelDemo"
width=250 Output of the Program
public void init()
height=150>
{</applet> */
Container
public classcontentPane =
getContentPane();
JLabelDemo ImageIcon ii = new
extends JApplet
ImageIcon("IC.jpg");
{JLabel jl = new JLabel("IC", ii,
JLabel.CENTER);
contentPane.add(jl);
}
}
17
TextFields

⚫ The Swing text field is encapsulated by the


JTextComponent class, which extends JComponent.
Constructors
⚫ JTextField( )
⚫ JTextField(int cols)
⚫ JTextField(String s, int cols)
⚫ JTextField(String s)

18
Example
: java.awt.*;
import
import
javax.swing.*;
/*<applet code="JTextFieldDemo" width=300 height=50></applet> */
public class JTextFieldDemo extends JApplet
{
JTextField jtf;
public void
init()
{ contentPane.setLayout(new Output of the Program
Conta
FlowLayout()); jtf = new
iner
JTextField(15); contentPane.add(jtf);
} conte
} ntPan
e=
getCo
ntent
19 Pane(
);
JComboBox

Combo box is a combination of text fields and drop-down


list.JComboBox component is used to create a combo box in
Swing.

Constructor for JComboBox


JComboBox()
JComboBox(String
arr[])

20
Methods used with
JComboBox
⚫ void addItem(Object anObject)
Adds an item to the item list.
⚫ void addItemListener(ItemListener aListener)
Adds an ItemListener.
⚫ Object getItemAt(int index)
Returns the list item at the specified index.
⚫ int getItemCount()
Returns the number of items in the list.
⚫ Object getSelectedItem()
Returns the current selected item.
⚫ void removeAllItems()
Removes all items from the item list.
⚫ void removeItem(Object anObject)
Removes an item from the item list.
⚫ void removeItemAt(int anIndex)
Removes the item at anIndex This method works only if the JComboBox
uses a mutable data model.
21
import javax.swing.*;
public class
JComboTest
{ JFrame f;
JComboTest
()
{
f=ne
w
JFra
me("
Com
bo
ex");
String country[]={"India","Aus","U.S.A","England","Newzeland"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500
);
2 f.setVisible(true);
2
f.setDefaultCloseO
Output of the Program

23
Buttons
⚫ Swing buttons provide features that are not found in the Button
class defined by the AWT. For example, we can associate an icon
with a Swing button.

⚫ Swing buttons are subclasses of the Abstract Button class, which


extends JComponent.

⚫ Abstract Button 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.
24
Method
⚫ void setDisabledIcon(Icon di)
⚫svoid setPressedIcon(Icon pi)
⚫ void setSelectedIcon(Icon si)
⚫ void setRolloverIcon(Icon ri)
⚫ String getText( )
⚫ void setText(String s)
⚫ String getActionCommand()- gets the text that is associated
with a button
⚫ void setActionCommand ()- sets the text that is associated with a
button

Concrete subclasses of AbstractButton generate action events when they


are pressed. Listeners register and un-register for these events via the
methods
⚫ void addActionListener(ActionListener al)
25
⚫ void removeActionListener(ActionListener al)
JButton
Constructors:

⚫ JButton(Icon i)
⚫ JButton(String s)
⚫ JButton(String s, Icon
i)

26
import java.awt.*;
import
javax.swing.*;
/*<applet code="JTextFieldDemo" width=250
{height=300></applet>*/ public class JButtonDemo extends Japplet
implementsjtf;
JTextField ActionListener
public void
init()
{
Container contentPane =
getContentPane();
contentPane.setLayout(new
FlowLayout()); ImageIcon f = new
ImageIcon("green.jpg"); JButton jb =
new JButton(f);
jb.setActionCommand("Green");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon g = new
ImageIcon("red.jpg"); jb = new
JButton(g);
2 jb.setActionCommand("Red");
7 jb.addActionListener(this); Engineering
jb = new JButton(i);
jb.setActionCommand("Yellow");
Output of the Program
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon j = new
ImageIcon("black.jpg");
jb = new JButton(j);
jb.setActionCommand("Black");
jb.addActionListener(this);
contentPane.add(jb);
jtf = new JTextField(15);
contentPane.add(jtf);
}
public void
actionPerformed(ActionEvent
ae)
{
jtf.setText(ae.getActionComma
nd());
}
}
CheckBoxe
s onstructors:
C
⚫ 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)
import java.awt.*;
import javax.swing.*;
import
java.awt.event.*;
/*<applet code="JCheckBoxDemo" width=400 height=50></applet>
*/ public class JCheckBoxDemo extends JApplet implements
ItemListener
{
JTextField jtf;
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new
FlowLayout()); JCheckBox cb = new
JCheckBox("C", true);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("C++",
false); cb.addItemListener(this);
cb = new JCheckBox("Java",
false); cb.addItemListener(this); Output of the Program
contentPane.add(cb);
cb = new JCheckBox("Perl",
false); cb.addItemListener(this);
contentPane.add(cb);
jtf = new JTextField(15);
contentPane.add(jtf);
}
public void
itemStateChanged(ItemEvent ie)
{
JCheckBox cb =
(JCheckBox)ie.getItem();
jtf.setText(cb.getText());
}
}
RadioButton
s
Constructors:
⚫ 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 button presses generate action events that are handled


by:
actionPerformed()
import java.awt.*;
import javax.swing.*;
Import
java.awt.event.*;
/*<applet code="
JRadioButtonDemo "
width=400
height=50></applet>
*/
public class
JRadioButtonDemo
extends JApplet
implements
ActionListener
{
JTextField tf;
public void
init()
{
Container contentPane =
getContentPane();
JRadioButton b3 = new
JRadioButton("C");
b3.addActionListener(this);
contentPane.add(b3);
ButtonGroup bg = new
ButtonGroup(); bg.add(b1);
bg.add(b2);
bg.add(b3);
tf = new
JTextField(5);
contentPane.add(tf);
}
public void
actionPerformed(Actio
nEvent ae)
{
tf.setText(ae.getAction
Command());
}
JPane
l
A panel is a swing container which is used for grouping
components which is later on added to the frame. In java
swing panel is implemented by JPanel class.
Constructors of

JPanel
JPanel()
Creates a panel.

 JPanel(LayoutManager)
The LayoutManager parameter provides a layout
manager for the new panel. By default, a panel uses a
FlowLayout to lay out its components.
import javax.swing.*;
import java.io.*;
class B
{
public
static void
main(Strin
g arg[])
{
J
F
r
a
m
e
f
=
n
e
w
Output of the Program
JTabbedPan
e
• JTabbedPane is a container component that lets the user switch
between pages by clicking on a tab.

• A tabbed pane is a component that appears as a group of tabs.


Each tab has a title. When a user selects a tab, its contents
become visible. Only one of the tab may be selected at a time.
Constructors for JTabbedPane
 JTabbedPane()
Creates an empty TabbedPane with a default tab placement
of JTabbedPane.TOP.

 JTabbedPane(int tabPlacement)
Creates an empty TabbedPane with the specified tab placement
of either: JTabbedPane.TOP, JTabbedPane.BOTTOM,
JTabbedPane.LEFT, or JTabbedPane.RIGHT.

 JTabbedPane(int tabPlacement, int tabLayoutPolicy)


Creates an empty TabbedPane with the specified tab
placement and tab layout policy.
The tab placement can be any of the
following:
⚫ JTabbedPane.TOP
⚫ JTabbedPane.BOTTOM
⚫ JTabbedPane.LEFT
⚫ JTabbedPane.RIGHT
Tab layout policy may be either of the
following:
⚫ JTabbedPane.WRAP_TAB_LAYOUT
⚫ JTabbedPane.SCROLL_TAB_LAYOUT
⚫ Wrap tab policy-

⚫ Scroll Tab
Policy-
Tabs are defined via the following
method:
void addTab(String str,
Component comp)
Here, str - the title for the
tab,
comp - is the
component that
should be added to the
tab.

The general procedure


to use a tabbed pane
import javax.swing.*;

/* <applet code="Demo" width=400 height=100> </applet>

*/ public class Demo extends JApplet


{
public void init()
{
JTabbedPane JTP = new JTabbedPane();
JTP.addTab(“Languages", new
LangPanel()); JTP.addTab("Colors", new
ColorsPanel()); JTP.addTab("Flavors", new
FlavorsPanel()); add(JTP);
}
}
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);
}
}
Output of the Program
JScrollPan
e
⚫ A JScrollPane provides a scrollable view of a component.

⚫ When screen real estate is limited, use a scroll pane to display a


component that is large or one whose size can change
dynamically. i.e. It represents a scrollpane which is a rectangular
area in which a component may be viewed.
Constructors of
JScrollPane
JScrollPane()
Create a scroll pane
JScrollPane(Component
com)
com is
component which is
added to scroll pane.
JScrollPane(int vsb,
int hsb)
vasb and hsb are int constants for controlling
vertical and horizontal scrolling.
JScrollPane(Component com, int vsb, int hsb)
int constants vsb and hsb
values
⚫ VERTICAL_SCROLLBAR_ALWAYS
Vertical scroll bar is always provided.

⚫ HORIZONTAL_SCROLLBAR_ALWAYS
Horizontal scroll bar is always provided.

⚫ VERTICAL_SCROLLBAR_AS_NEEDED
Vertical scroll bar is provided as per the
need.

⚫ HORIZONTAL_SCROLLBAR_AS_NEEDED
Horizontal scroll bar is provided as per the
need.
import javax.swing.*;
import java.awt.*;
/*<applet code="JScrollPaneDemo" width=300 height=250> </applet>
*/ 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, Output of the Program
BorderLayout.CENTER);
}
}
JTre
⚫e
The JTree class is used to display the tree structured data or
hierarchical data.
⚫ It has a 'root node' at the top most which is a parent for all nodes in
the tree. It inherits JComponent class.
The java.swing package provides the JTree and its component.

 JTree: The tree is a special type of graph that designed for displaying data with the
hierarchical properties by adding nodes to nodes and keeps the concept of parent and
child node.

 Node: A node is an object at any position within the JTree where the data are
associated or being represented.

 Path: The path is the collection of contiguous set of nodes that contains one or many
nodes.The path is empty or null when the path has not any node.

 Leaf: This is a special types of node at the end of a path. The leaf node has
not
connected to more nodes.

 Root: This is the node of highest point within the hierarchy in tree.

 Parent: It represents the relationship of node with another node.

 Child: It represents the relationship of node with another node.


Constructors Of
JTree
⚫ JTree(Object[] value)
Returns a JTree with each element of the specified array as the
child of a new root node which is not displayed. Each element of the
array object is childnode.

⚫ JTree(TreeNode tn)
Returns a JTree with the specified TreeNode as its root, which
displays the root node.Treenode tn is the root of the tree.

⚫ JTree(Vector v)
Returns a JTree with each element of the specified Vector as the
child of a new root node which is not displayed. Elements of vector v is
the childnode
⚫ MutableTreeNode interface declares methods to
obtain information about a tree node.

⚫ The‘MutableTreeNode’ interface extends ‘TreeNode’ class.

⚫ DefaultMutableTreeNode represents a node in a tree.

⚫ The ‘DefaultMutableTreeNode’ class


implements the ‘MutableTreeNode’
interface.
Methods used with JTree
DefaultMutableTreeNode(object obj)
where‘obj’ is the object to be enclosed in this tree node.

void add(MutableTreeNode child)


This method can be used to create the hierarchy of nodes .where
‘child’ is the mutable treenode this is to be added as a child to
the current node.

TreePath getPathForLocation(int x, int y)


It is used to translate a mouse click on a point of tree to a tree
path.Where, x and y are coordinates of mouse click.
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample
{
JFrame f;
TreeExample()
{
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color
);
style.add(font);
DefaultMutable
TreeNode
red=new
DefaultMutable
TreeNode("red"
);
DefaultMutable
TreeNode
blue=new
DefaultMutable
JTree jt= new
JTree(style); f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] Output of the Program
args)
{
new TreeExample();
} }
JTabl
eThe JTable class is used to display the data on two
dimensional tables of cells.

Constructors of JTable class:


 JTable()
creates a table with empty cells.

 JTable(Object[] rows, Object[] columns)


creates a table with the specified data.
import javax.swing.*;
public class MyJTable extends JFrame
{ MyJTable()
{
String data[]
[]={ {"101","Umesh","67
0000"},
{"102","Vij
ay","7800
00"},
{"101","Ra
hul","700
000"}};
String
column[]={"ID","NAME","
SALARY"};
JTable jt=new
JTable(data,column);
jt.setBounds(30,40,200,300);

JScrollPane sp=new JScrollPane(jt);


add(sp);

setSize(300,400);
Output of the Program
JProgressBar
The class JProgressBar is a component which visually
displays the progress of some task.
Constructors of
JProgessBar
 JProgressBar()
Creates a horizontal progress bar that displays a border but no progress string.

 JProgressBar(int orient)
Creates a progress bar with the specified orientation, which can be
either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.

 JProgressBar(int min, int max)


Creates a horizontal progress bar with the specified minimum and maximum
values.

 JProgressBar(int orient, int min, int max)


Creates a progress bar using the specified orientation, minimum and maximum
values.
Methods used with
JProgressBar
⚫void setStringPainted(boolean b)
Determines whether the progress bar should display a progress string.

⚫ int getMaximum()
Returns the progress bar's maximum value

⚫ int getMinimum()
Returns the progress bar's minimum value from the
BoundedRangeModel.

⚫ int getOrientation()
Returns SwingConstants.VERTICAL or SwingConstants.HORIZONTAL,
depending on the orientation of the progress bar.
import javax.swing.*;
public class MyProgress extends Jframe
{
JProgressBar jb;
int i=0,num=0;

MyProgress()
{
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,200,30);

jb.setValue(0);
jb.setStringPainted(true);

add(jb);
setSize(400,400
);
setLayout(null);
}
setDefaultCloseOpe
ration(JFrame.EXI
T_ON_CLOSE);
public void iterate()
{
while(i<=2000)
{
jb.setValue(i
); i=i+20;
try
{
Thread.sl
eep(150)
;
}
catch(Excep
tion e){}
}
}
public static void
main(String[]
args)
{
MyProgress m=new
MyProgress(); m.setVisible(true);
Output of the Program
ToolTi
p
Tooltip text is normally one line long. The
setToolTipText() method from JComponent used to create a
tooltip.

public void setToolTipText(String text)


Registers the text to display in a tool tip. The text
displays when the cursor lingers over the component.
MVC Architecture
Swing API architecture follows MVC architecture. The MVC
design pattern consists of three modules: model, view and controller.

Model -The model represents the state (data) and business logic of the
application.

View -The view module is responsible to display data i.e. it


represents
the presentation.

Controller -The controller module acts as an interface between view


and model. It intercepts all the requests i.e. receives input and commands
to Model / View to change accordingly.
UML Diagram MVC Design Pattern

You might also like