Ajp Notes Chapter 02
Ajp Notes Chapter 02
Ajp Notes Chapter 02
Chapter 02
The Tour of Swing
Contents:
2.1 Japplet
Icons and Labels
Text Fields
Buttons
Combo Boxes
Checkboxes
Tabbed Panes
Scroll Panes
2.2 Trees
Tables
Exploring the Swings
Introduction
Object java.lang
Component
Container
java.awt
MenuContainer Window
Interface
Frame
JFrame javax.swing
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.
Object java.lang
Component
Container
JComponent
Window
JFrame
Besides the large array of components in Swing and the fact that they are
lightweight, Swing introduces many other innovations.
2.2.1 Borders
We can draw borders in many different styles around components
using the setborder( ) method.
2.2.4 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.
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. 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.
JApplet
Container getContentPane( )
void add(comp)
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. The ImageIcon class
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, 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.
JLabel(Icon i)
Label(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 constants are
defined in the SwingConstants interface, along with several others used by the
Swing classes. 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)
Here, i and s are the icon and text, respectively. The following example
illustrates how to create and display a label containing both an icon and a
string. The applet begins by getting its content pane. Next, an ImageIcon
object is created for the file IC.jpg. This is used as the second argument to the
JLabel constructor. The first and last arguments for the JLabel constructor are
the label text and the alignment. Finally, the label is added to the content pane.
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
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 that control this behavior:
Here, di, pi, si, and ri are the icons to be used for these different
conditions. The text associated with a button can be read and written via the
following methods:
String getText( )
void setText(String s)
JButton Class
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
Here, s and i are the string and icon used for the button. The following
example displays four push buttons and a text field. Each button displays an
icon that represents the flag of a country. When a button is pressed, the name
of that country is displayed in the text field. The applet begins by getting its
content pane and setting the layout manager of that pane. Four image buttons
are created and added to the content pane. Next, the applet is registered to
receive action events that are generated by the buttons. A text field is then
created and added to the applet. Finally, a handler for action events displays
the command string that is associated with the button. The text field is used to
present this string.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JButtonDemo" width=250 height=300>
</applet>
*/
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
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)
Here, 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:
Here, state is true if the check box should be checked. The following
example illustrates how to create an applet that displays four check boxes and
a text field. When a check box is pressed, its text is displayed in the text field
the content pane for the JApplet object is obtained, and a flow layout is
assigned as its layout manager. Next, four check boxes are added to the
content pane, and icons are assigned for the normal, rollover, and selected
states. The applet is then registered to receive item events. Finally, a text field
is added to the content pane. 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 tex for that check box and
uses it to set the text inside the text field.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<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);
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();
jtf.setText(cb.getText());
}
}
Radio Buttons
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)
Here, i is the icon for the button. The text is specified by s. If state istrue,
the button is initially selected. Otherwise, it is not. Radio buttons must be
configured into a group. Only one of the buttons in that group can be selected
at any time. For example, if a user presses a radio button that is in a group,
any previously selected button in that group is automatically deselected.
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:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet
implements ActionListener
{
JTextField tf;
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
Combo Boxes
JComboBox( )
JComboBox(Vector v)
JComboBox(Objects obj[])
Here, v is a vector that initializes the combo box and obj is the array of
objects. Items are added to the list of choices via the addItem( ) method,
whose signature is shown here:
Important Methods:
The following example contains a combo box and a label. The label
displays an icon. The combo box contains entries for colors Green, Red, Yellow
and Black. When a country is selected, the label is updated to display the color
for that particular color. Color jpeg images are already stored in the current
directory.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JComboBoxDemo" width=300 height=100>
</applet>
*/
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
JTabbedPane()
JTabbedPane(int tabPlacement)
JTabbedPane(int tabPlacement, int tabLayoutPolicy)
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 of any of the following:
JTabbedPane.TOP
JTabbedPane.BOTTOM
JTabbedPane.LEFT
JTabbedPane.RIGHT
JTabbedPane.WRAP_TAB_LAYOUT
JTabbedPane.SCROLL_TAB_LAYOUT
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 is added. 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.
The following example illustrates how to create a tabbed pane. The first
tab is titled Languages and contains four buttons. Each button displays the
name of a language. The second tab is titled Colors and contains three check
boxes. Each check box displays the name of a color. The third tab is titled
Flavors and contains one combo box. This enables the user to select one of
three flavors.
import javax.swing.*;
/*
<applet code="JTabbedPaneDemo" width=400 height=100>
</applet>
*/
Scroll Panes
JScrollPane()
JScrollPane(Component comp)
JScrollPane(int vsb, int hsb)
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. Some examples of these constants are
described as follows:
Constant Description
HORIZONTAL_SCROLLBAR_ALWAYS Always provide horizontal scroll
bar
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
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.)
import java.awt.*;
import javax.swing.*;
/*
<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, BorderLayout.CENTER);
}
Trees
JTree(Hashtable ht)
JTree(Object obj[ ])
JTree(TreeNode tn)
JTree(Vector v)
The first form creates a tree in which each element of the hash table ht is
a child node. Each element of the array obj is a child node in the second form.
The tree node tn is the root of the tree in the third form. Finally, the last form
uses the elements of vector v as child nodes. A JTree object generates events
when a node is expanded or collapsed. The addTreeExpansionListener( ) and
removeTreeExpansionListener( ) methods allow listeners to register and
unregister for these notifications. The signatures of these methods are shown
here:
Here, x and y are the coordinates at which the mouse is clicked. The
return value is a TreePath object that encapsulates information about the tree
node that was selected by the user. The TreePath class encapsulates
information about a path to a particular node in a tree. It provides several
constructors and methods.
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.
MutableTreeNode TreeNode
DefaultMutableTreeNode
DefaultMutableTreeNode(Object obj)
Here, obj is the object to be enclosed in this tree node. 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:
TreePath getPath( )
Here, tee is the tree expansion event. The first method is called when a
sub-tree is hidden, and the second method is called when a sub-tree becomes
visible. Here are the steps that we should follow to use a tree in an 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;
JTextField jtf;
public void init()
{
Container contentPane=getContentPane();
contentPane.setLayout(new BorderLayout());
DefaultMutableTreeNode top=new
DefaultMutableTreeNode("Options");
DefaultMutableTreeNode a= new DefaultMutableTreeNode("A");
top.add(a);
DefaultMutableTreeNode a1=new DefaultMutableTreeNode("A1");
a.add(a1);
DefaultMutableTreeNode a2=new DefaultMutableTreeNode("A2");
a.add(a2);
DefaultMutableTreeNode b= new DefaultMutableTreeNode("B");
top.add(b);
DefaultMutableTreeNode b1=new DefaultMutableTreeNode("B1");
b.add(b1);
DefaultMutableTreeNode b2=new DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3=new DefaultMutableTreeNode("B3");
b.add(b3);
tree=new JTree(top);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp=new JScrollPane(tree,v,h);
contentPane.add(jsp,BorderLayout.CENTER);
jtf=new JTextField("",20);
contentPane.add(jtf,BorderLayout.SOUTH);
tree.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
doMouseClicked(me);
}
});
}
void doMouseClicked(MouseEvent me)
{
TreePath tp=tree.getPathForLocation(me.getX(),me.getY());
if(tp!=null)
jtf.setText(tp.toString());
else
jtf.setText("");
}
}
The string presented in the text field describes the path from the top tree
node to the selected node.
Tables
The following example illustrates how to create and use a table. The
content pane of the JApplet object is obtained and a border layout is assigned
as its layout manager. 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 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
content pane.
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" };
final Object[][] data = {
------------------
References
----------------