0% found this document useful (0 votes)
13 views41 pages

The Tour of Swing

java swing
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)
13 views41 pages

The Tour of Swing

java swing
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/ 41

SWING

Japplet
Ø Icons and Labels
Ø Text Fields
Ø Buttons
Ø Combo Boxes
Ø Checkboxes
Ø Tabbed Panes
Ø Scroll Panes
Ø Exploring the Swings
Ø Tables
Ø Tree
INTRODUCTION
 Swing is a set of classes this provides more powerful and
flexible components than are possible with the AWT.
 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.
 Even familiar components such as buttons have more
capabilities in Swing. For example, 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. Unlike AWT components, Swing components are
not implemented by platform-specific code.
 The Swing component classes that are shown below:
Class Description
Ø AbstractButton:- Abstract super-class for Swing buttons.
Ø 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.
Ø 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
Java Swing class hierarchy
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 among the other things,
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.
……..CONTINUE
 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
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. For example, JApplet supports
various “panes,” such as the content pane, the
glass pane, and the root pane.
 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
theJApplet object. method shown here:
Container getContentPane( )
 Its form is shown here:

void add(comp)
ICONS AND LABELS
 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)
 implements the Icon interface that declares the methods shown here:
 Method Description
 int getIconHeight( ) Returns the height of the icon in pixels.
 int getIconWidth( ) Returns the width of the icon in pixels.
 void paintIcon(Component comp, Paints the icon at Graphics g, int x, int y)
position x,y on the graphics context
g.additional information about the paint
operation can be provided in comp.
 Swing labels are instances of the JLabel class, which extends JComponent. It can
display text and/or an icon. Some of its constructors are
JLabel(Icon i)
Label(String s)
JLabel(String s, Icon i, int align)
 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)
import java.awt.*;
import javax.swing.*;
/* <applet code="JLabelDemo" width=250 height=150> </applet> */
public class JLabelDemo extends JApplet
{
public void init()
{
Container contentPane = getContentPane();
ImageIcon ii = new ImageIcon("IC.jpg");
JLabel jl = new JLabel("IC", ii, JLabel.CENTER);
contentPane.add(jl);}}
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)
JTextField(String s, int cols)
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);}}
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 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. The following are the methods
void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si) void setRolloverIcon(Icon ri)
JBUTTON CLASS

 The JButton class provides the functionality of a push button.


Jbutton allows an icon string, or both to be associated with the push
button.
 constructors are shown here:
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
import java.awt.*;
import java.awt.event.*;
import java.swing.*;
public class JButtonDemo extends JApplet
implements ActionListener {
JTextField jtf;
public void init() {
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
ImageIcon france = new ImageIcon("green.jpg");
JButton jb = new JButton(france);
jb.setActionCommand("Green");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon germany = new ImageIcon("red.jpg");
jb = new JButton(germany);
jb.setActionCommand("Red");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon italy = new ImageIcon("yellow.jpg");
jb = new JButton(italy);
jb.setActionCommand("Yellow");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon japan = new ImageIcon("black.jpg");
jb = new JButton(japan);
jb.setActionCommand("Black");
jb.addActionListener(this);
contentPane.add(jb);
jtf = new JTextField(15);
contentPane.add(jtf);}
public void actionPerformed(ActionEvent ae)
{
jtf.setText(ae.getActionCommand());
}
}
CHECK BOXES
 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)
 i is the icon for the button. The text is specified by s. If state is
true, the check box is initially selected. Otherwise, it is not. The
state of the check box can be changed via the following method:
void setSelected(boolean state)
import java.awt.*; import java.awt.event.*;import javax.swing.*;
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);
contentPane.add(cb);
cb = new JCheckBox("Java", false);
cb.addItemListener(this);
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();
RADIO BUTTONS
Radio buttons are supported by the RadioButton
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)
 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)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JRadioButtonDemo extends Japplet implements ActionListener {
JTextField tf;
public void init() {
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
contentPane.add(b1);
JRadioButton b2 = new JRadioButton("B");
b2.addActionListener(this);
contentPane.add(b2);
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(ActionEvent ae) {
tf.setText(ae.getActionCommand()); } }
COMBO BOXES
 Swing provides a combo box (a combination of a text field and a
drop- down 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. Two of
JComboBox’s constructors are shown here:
JComboBox( )
 JComboBox(Vector v):- v is a vector that initializes the combo box
and obj is the array of objects.
JComboBox(Objects obj[]):-Items are added to the list of choices via
the addItem( ) method,void addItem(Object obj).
 Important Methods:
Ø public void setEditable(boolean aFlag) :-It determines 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. If the number of objects in
the model is greater than ‘count’, the combo box uses a scrollbar.
Ø public void setSelectedItem(Object anObject) :-It sets the selected
item in the combo box display area to the object in the argument. If
anObject is in the list, the display area shows anObject selected.
Ø public void insertItemAt(Object anObject, int index) :-It inserts an
item ‘anObject’ into the item list at a given ‘index’.
Ø public void removeItem(Object anObject):-It removes an item
‘anObject’ from the item list.
Ø public void removeItemAt(int anIndex) :- It removes the item at
‘anIndex’.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JComboBoxDemo extends JApplet
implements ItemListener {
JLabel jl;
ImageIcon green, red, black, yellow;
public void init() {
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
JComboBox jc = new JComboBox();
jc.addItem("Green");
jc.addItem("Red");
jc.addItem("Black");
jc.addItem("Yellow");
jc.addItemListener(this);
contentPane.add(jc);
jl = new JLabel(new ImageIcon("green.jpg"));
contentPane.add(jl); }
public void itemStateChanged(ItemEvent ie) {
String s = (String)ie.getItem();
jl.setIcon(new ImageIcon(s + ".jpg")); }}
TABBED PANES
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. 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.
 JTabbedPane():-The first form creates an empty TabbedPane with
a default tab placementof JTabbedPane top.
 JTabbedPane(int tabPlacement):-Second form creates an empty
TabbedPane with the specified tab placement of any.
JTabbedPane.TOP,JTabbedPane.BOTTOM,JTabbedPane.LEFT
JTabbedPane.RIGHT
 JTabbedPane(int tabPlacement, int tabLayoutPolicy):-constructor
creates an empty TabbedPane with the specified tab placement and
tab layout policy.
 Tab placements are listed above. Tab layout policy may be either of
the following:
JTabbedPane.WRAP_TAB_LAYOUT
JTabbedPane.SCROLL_TAB_LAYOUT
 Tabs are defined via the following method:

void addTab(String str, Component comp)


THE GENERAL PROCEDURE TO USE A TABBED PANE IN
AN APPLET IS OUTLINED HERE:

1. Create a JTabbedPane object.


2. Call addTab( ) to add a tab to the pane. (The
arguments to this method define the title of the
tab and the component it contains.)
3. Repeat step 2 for each tab.
4. Add the tabbed pane to the content pane of the
applet.
import javax.swing.*;
public class JTabbedPaneDemo extends Japplet { JCheckBox cb2 = new
public void init() {
JCheckBox("Green"); add(cb2);
JTabbedPane jtp = new JTabbedPane(); JCheckBox cb3 = new
jtp.addTab("Languages", new LangPanel()); JCheckBox("Blue"); add(cb3); } }
jtp.addTab("Colors", new ColorsPanel()); class FlavorsPanel extends Jpanel {
jtp.addTab("Flavors", new FlavorsPanel()); public FlavorsPanel() {
getContentPane().add(jtp); } }
JComboBox jcb = new JComboBox();
class LangPanel extends Jpanel {
public LangPanel() {
jcb.addItem("Vanilla");
JButton b1 = new JButton("Marathi"); add(b1); jcb.addItem("Chocolate");
JButton b2 = new JButton("Hindi"); add(b2); jcb.addItem("Strawberry"); add(jcb); }
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);
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.
 Some of its constructors are shown here:
JScrollPane()
JScrollPane(Component comp)
JScrollPane(int vsb, int hsb)
JScrollPane(Component comp, int vsb, int hsb)
Constant Description
HORIZONTAL_SCROLLBAR_ALWAYS :-Always provide horizontal scrollbar
HORIZONTAL_SCROLLBAR_AS_NEEDED :-Provide horizontal scroll bar, if needed
VERTICAL_SCROLLBAR_ALWAYS :-Always provide vertical scroll bar
VERTICAL_SCROLLBAR_AS_NEEDED :- Provide vertical scroll bar, if needed.
 use a scroll pane in an applet:
1. Create a JComponent object.
2. Create a JScrollPane object. (The arguments to the constructor specify
3. the component and the policies for vertical and horizontal scroll bars.)
4. Add the scroll pane to the content pane of the applet.
import java.awt.*;
import javax.swing.*;
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.
 Trees are implemented in Swing by the JTree class, which
extends JComponent.
 JTree(Hashtable ht) :-Creates a tree in which each element
of the hash table ht is a child node
JTree(Object obj[ ]) :-Each element of the array obj is a child
node
JTree(TreeNode tn):-The tree node tn is the root of the tree.
JTree(Vector v) :-Uses the elements of vector v as child nodes.
 The signatures of these methods are shown here:
void addTreeExpansionListener(TreeExpansionListener tel)
void removeTreeExpansionListener(TreeExpansionListener tel)
 The getPathForLocation( ) method is used to translate a
mouse click on a specific point of the tree to a tree path. Its
signature is shown here:
TreePath getPathForLocation(int x, int y)
 The TreeNode interface declares methods that obtain
information about a tree node. For example, it is possible
to obtain a reference to the parent node or an enumeration
of the child nodes. The MutableTreeNode interface
extends TreeNode. It declares methods that can insert and
remove child nodes or change the parent node
 The DefaultMutableTreeNode class implements the
MutableTreeNode interface.
DefaultMutableTreeNode(Object obj)
MutableTreeNode
TreeNode

DefaultMutableTreeNode
 The new tree node doesn’t have a parent or children. To
create a hierarchy of tree nodes, the add( ) method of
DefaultMutableTreeNode can be used. Its signature is
shown here:
void add(MutableTreeNode child)
 Here, child is a mutable tree node that is to be added as a
child to the current node.
 Tree expansion events are described by the class
TreeExpansionEvent in the javax.swing.event package.
 The getPath( ) method of this class returns a TreePath
object that describes the path to the changed node. e:
ddTreePath getPath( )
 The TreeExpansionListener interface provides the
following two method:
void treeCollapsed(TreeExpansionEvent tee)
void treeExpanded(TreeExpansionEvent tee)
The steps that we should follow to use a tree in an applet:
1. Create a JTree object.

2. Create a JScrollPane object. (The arguments to the


constructor specify
3. the tree and the policies for vertical and horizontal scroll
bars.)
4. Add the tree to the scroll pane.

5. Add the scroll pane to the content pane of the applet.


import java.awt.*;import java.awt.event.*; b.add(b2);
import javax.swing.*; import javax.swing.tree.*; DefaultMutableTreeNode b3=new
public class JTreeEvents extends Japplet { DefaultMutableTreeNode("B3");

JTree tree; JTextField jtf; b.add(b3); tree=new JTree(top);

public void init() { int


v=ScrollPaneConstants.VERTICAL_SCROLLBAR_
Container contentPane=getContentPane(); AS_NEEDED;
contentPane.setLayout(new BorderLayout()); int
DefaultMutableTreeNode top=new h=ScrollPaneConstants.HORIZONTAL_SCROLLBA
R_AS_NEEDED;
DefaultMutableTreeNode("Options");
JScrollPane jsp=new JScrollPane(tree,v,h);
DefaultMutableTreeNode a= new
DefaultMutableTreeNode("A"); contentPane.add(jsp,BorderLayout.CENTER);
top.add(a); jtf=new JTextField("",20);
DefaultMutableTreeNode a1=new contentPane.add(jtf,BorderLayout.SOUTH);
DefaultMutableTreeNode("A1"); tree.addMouseListener(new MouseAdapter(){
a.add(a1); public void mouseClicked(MouseEvent me){
DefaultMutableTreeNode a2=new doMouseClicked(me);}});}
DefaultMutableTreeNode("A2");
void doMouseClicked(MouseEvent me){
a.add(a2);
TreePath
DefaultMutableTreeNode b= new tp=tree.getPathForLocation(me.getX(),me.getY());
DefaultMutableTreeNode("B");
if(tp!=null)
top.add(b);
jtf.setText(tp.toString());
DefaultMutableTreeNode b1=new
DefaultMutableTreeNode("B1"); else

b.add(b1); jtf.setText(""); }}

DefaultMutableTreeNode b2=new
DefaultMutableTreeNode("B2");
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[ ]):-data is a two-dimensional array of the
information to be presented, and colHeads is a one-dimensional array with the column
headings.
JTable(int numRows, int numColumns):- The ‘numRows’ and ‘numColumns’ are values with
which the table is to be created.
JTable(Vector rowData, Vector columnData):-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:
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.
4. Add the scroll pane to the content pane of the applet
import java.awt.*;
import javax.swing.*;
public class JTableDemo extends JApplet{
public void init(){
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
final String[] colHeads = { "Name", "Phone", "Fax" };
final Object[][] data = {{ "Pramod", "4567", "8675" },{ "Tausif", "7566", "5555" },
{ "Nitin", "5634", "5887" },{ "Amol", "7345", "9222" },{ "Vijai", "1237", "3333" },
{ "Ranie", "5656", "3144" },{ "Mangesh", "5672", "2176" },{ "Suhail", "6741", "4244" },
{ "Nilofer", "9023", "5159" },{ "Jinnie", "1134", "5332" },{ "Heena", "5689", "1212" },
{ "Saurav", "9030", "1313" },{ "Raman", "6751", "1415" } };
JTable table = new JTable(data, colHeads);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
contentPane.add(jsp, BorderLayout.CENTER);
}}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy