AJP CHP 2
AJP CHP 2
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.
4
Hierarchy of Java Swing
classes
5
Using Top-Level
Containers
Swing provides three generally useful top- container
level classes: JFrame, JDialog, and JApplet.
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.
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
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
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
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.
⚫ 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
⚫ 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)
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.
JTabbedPane(int tabPlacement)
Creates an empty TabbedPane with the specified tab placement
of either: JTabbedPane.TOP, JTabbedPane.BOTTOM,
JTabbedPane.LEFT, or JTabbedPane.RIGHT.
⚫ 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.
⚫ 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.
⚫ 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.
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.
⚫ 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.
Model -The model represents the state (data) and business logic of the
application.