Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Introduction to swing
1.1 Swing (Nov 2006- Q-3(b))
Q-3(b) Explain what is a swing? List the advantages of Swing.
• Swing is a set of classes that provides more powerful and flexible components
than are possible with the AWT.
• Swing provides a set of "lightweight" (all-Java language) components that, to the
maximum degree possible, work the same on all platforms.
• The term lightweight is used to describe such elements. The Swing component
classes that are used are shown here:
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 (an 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.
• Fundamental to Swing is the JApplet class, which extends Applet. Applets that
use Swing must be subclasses of JApplet.
• JApplet are specialized components that provide a place for other Swing
components to paint themselves.
• 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 the JApplet
object.
• The content pane can be obtained via the method shown here:
Container 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)
Here, comp is the component to be added to the content pane.
• Example:-
// JApplet Example Code
import java.awt.*;
import javax.swing.*;
public class JAppletExample extends JApplet
{
public void init()
{
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));
content.add(new JButton("Button 2"));
content.add(new JButton("Button 3"));
}
}
Icons:-
• In Swing, icons are encapsulated by the ImageIcon class, which paints an icon
from an image.
• Two of its constructors are shown here:
1. ImageIcon(String filename):- Creates an ImageIcon from the specified
file.
ImageIcon(URL url):- Creates an ImageIcon from the specified URL.
• The ImageIcon class implements the Icon interface that declares the methods
shown here:
• Method
1. int getIconHeight( )- Returns the height of the icon in pixels.
2. int getIconWidth( )- Returns the width of the icon in pixels.
3. 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.
Labels:-
• Swing labels are instances of the JLabel class, which extends JComponent. It
can display text and/or an icon.
• Some of its constructors are shown here:
1. JLabel(Icon i):- Creates a JLabel instance with the specified image.
2. JLabel(String s):- Creates a JLabel instance with the specified text.
3. JLabel(String s, Icon i, int align):- Creates a JLabel instance with the
specified text, image, and horizontal alignment. The align argument is
either LEFT, RIGHT, or CENTER. 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:
1. Icon getIcon( ):- Returns the graphic image (glyph, icon) that the label
displays.
2. String getText( ):- Returns the text string that the label displays.
3. void setIcon(Icon i):- Defines the icon this component will display.
4. void setText(String s):- Defines the single line of text this component
will display.
Example:-
• 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 france.gif. 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()
{
// Get content pane
Container contentPane = getContentPane();
// Create an icon
ImageIcon ii = new ImageIcon("france.gif");
// Create a label
JLabel jl = new JLabel("France", ii, JLabel.CENTER);
// Add label to the content pane
contentPane.add(jl);
}
}
Output from this applet is shown here:
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet
{
JTextField jtf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Add text field to content pane
jtf = new JTextField(15);
contentPane.add(jtf);
}
}
• Output from this applet is shown here:
1.4.1 JTextArea
• A JTextArea is used to accept multi-line input from the user.
• The java.awt.TextArea internally handles scrolling. JTextArea is different in
that it doesn't manage scrolling, but implements the swing Scrollable interface.
This allows it to be placed inside a JScrollPane if scrolling behavior is desired,
and used directly if scrolling is not desired.
• The java.awt.TextArea has the ability to do line wrapping. This was controlled
by the horizontal scrolling policy.
• JTextArea has a bound property for line wrapping that controls whether or not it
will wrap lines. By default, the line wrapping property is set to false (not
wrapped).
• java.awt.TextArea has two properties rows and columns that are used to
determine the preferred size. If the value for rows or columns is equal to zero, the
preferred size along that axis is used for the viewport preferred size along the
same axis.
• The java.awt.TextArea could be monitored for changes by adding a
TextListener for TextEvents.
• Constructors:-
1. JTextArea():-Constructs a new TextArea.
2. JTextArea(Document doc) :-Constructs a new JTextArea with the given
document model, and defaults for all of the other arguments (null, 0, 0).
3. JTextArea(Document doc, String text, int rows,
int columns) :-Constructs a new JTextArea with the specified number of
rows and columns, and the given model.
4. JTextArea(int rows, int columns):-Constructs a new empty TextArea
with the specified number of rows and columns.
5. JTextArea(String text):-Constructs a new TextArea with the specified
text displayed.
6. JTextArea(String text, int rows, int columns):-Constructs a new
TextArea with the specified text and number of rows and columns.
1.5 Buttons
• Swing buttons provide features that are not found in the Button class defined by
the AWT.
• For example, you 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 you to control the behavior of
buttons, check boxes, and radio buttons.
• For example, you can define different icons that are displayed for the component
when it is disabled, pressed, or selected. Another icon can be used as a rollover
icon, which is displayed when the mouse is positioned over that component.
• The following are the methods that control this behavior:
1. void setDisabledIcon(Icon di):-Sets the disabled icon for the button.
2. void setPressedIcon(Icon pi):- Sets the pressed icon for the button.
3. void setSelectedIcon(Icon si):- Sets the selected icon for the button.
4. void setRolloverIcon(Icon ri):- Sets the rollover icon for the button
• The text associated with a button can be read and written via the following
methods:
1. String getText( ):- Returns the button's text.
2. void setText(String s):- Sets the button's text.
• Concrete subclasses of AbstractButton generate action events when they are
pressed. Listeners register and unregistered for these events via the methods
shown here:
void addActionListener(ActionListener al)
void removeActionListener(ActionListener al)
Here, al is the action listener.
import java.awt.*;
import javax.swing.*;
public class JButtons extends JFrame {
public static void main(String[] args) {
new JButtons();
}
public JButtons() {
super("Using JButton");
//WindowUtilities.setNativeLookAndFeel();
//addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
JButton button1 = new JButton("Java");
content.add(button1);
ImageIcon cup = new ImageIcon("iso.gif");
JButton button2 = new JButton(cup);
content.add(button2);
JButton button3 = new JButton("Java", cup);
content.add(button3);
JButton button4 = new JButton("Java", cup);
button4.setHorizontalTextPosition
(SwingConstants.LEFT);
content.add(button4);
pack();
setVisible(true);
}}
• Example:- 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. 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 text 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()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Create icons
ImageIcon normal = new ImageIcon("normal.gif");
ImageIcon rollover = new ImageIcon("rollover.gif");
ImageIcon selected = new ImageIcon("selected.gif");
// Add check boxes to the content pane
JCheckBox cb = new JCheckBox("C", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("C++", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Java", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Perl", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
// Add text field to the content pane
jtf = new JTextField(15);
contentPane.add(jtf);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb = (JCheckBox)ie.getItem();
jtf.setText(cb.getText());
}
}
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()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Add radio buttons to content pane
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);
// Define a button group
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
// Create a text field and add it
// to the content pane
tf = new JTextField(5);
contentPane.add(tf);
}
public void actionPerformed(ActionEvent ae)
{
tf.setText(ae.getActionCommand());
}
}
1.9 Container
• A container is a kind of component that holds and manages other components.
JComponent objects can be containers because the JComponent class descends
from the Container class. However, you wouldn't normally add components
directly to specialized components such as buttons or lists.
• Three of the most useful general container types are JFrame, JPanel, and
JApplet.
• A JFrame is a top-level window on your display. JFrame is derived from
JWindow, which is pretty much the same but lacks a border.
• A JPanel is a generic container element that groups components inside JFrames
and other JPanels.
• The JApplet class is a kind of container that provides the foundation for applets
that run inside web browsers. Like other JComponents, a JApplet can contain
other user-interface components.
• You can also use the JComponent class directly, like a JPanel, to hold
components inside another container. With the exception of JFrame and JWindow,
all the components and containers in Swing are lightweight.
• The add() method of the Container class adds a component to the container.
Thereafter, this component can be displayed in the container's display area and
positioned by its layout manager. You can remove a component from a container
with the remove() method.
frame.setVisible(true);
window.setVisible(true);
}
}
• The JFrame constructor can take a String argument that supplies a title,
displayed in the JFrame's titlebar. After creating the JFrame, we create a JWindow
in almost exactly the same way. The JWindow doesn't have a titlebar, so there are
no arguments to the JWindow constructor.
import java.awt.*;
import javax.swing.*;
frame.pack( );
frame.setVisible(true);
}
}
1.9.3 JPanel
• Example:-
• Output is:
1.12 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.
• Scrollpanes are implemented in Swing by the JScrollPane class, which extends
JComponent.
• Some of its constructors are shown here:
1. JScrollPane(Component comp):- Creates a JScrollPane that displays
the contents of the specified component, where both horizontal and
vertical scrollbars appear whenever the component's contents are larger
than the view.
2. JScrollPane(int vsb, int hsb):- Creates an empty (no viewport view)
JScrollPane with specified scrollbar constants.
3. JScrollPane(Component comp, int vsb, int hsb):- Creates a
JScrollPane that displays the view component in a viewport whose view
position can be controlled with a pair of scrollbars.
• These constants are defined by the ScrollPaneConstants interface. Some
examples of these constants are described as follows:
1. HORIZONTAL_SCROLLBAR_ALWAYS:- Always provide horizontal
scroll bar
2. HORIZONTAL_SCROLLBAR_AS_NEEDED:- Provide horizontal scroll
bar, if needed
3. VERTICAL_SCROLLBAR_ALWAYS:- Always provide vertical scroll bar
4. VERTICAL_SCROLLBAR_AS_NEEDED:-Provide vertical scroll bar, if
needed
• Following steps that you should follow to use a scroll pane in an applet:
1. Create a JComponent object.
2. Create a JScrollPane object.
3. Add the scroll pane to the content pane of the applet.
• The following example illustrates a scroll pane. First, the content pane of the JApplet
object is obtained and a border layout is assigned as its layout manager. Next, a
JPanel object is created and four hundred buttons are added to it, arranged into
twenty columns.The panel is then added to a scroll pane, and the scroll pane is added
to the content pane. This causes vertical and horizontal scroll bars to appear. You can
use the scrollbars to scroll the buttons into view.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
public class JScrollPaneDemo extends JApplet
{
public void init()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
// Add 400 buttons to a panel
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;
}
}
// Add panel to a scroll pane
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(jp, v, h);
// Add scroll pane to the content pane
contentPane.add(jsp, BorderLayout.CENTER);
}
}
• Output from this applet is shown here:
1.13 Tables
• A table is a component that displays rows and columns of data. You can drag the
cursor on column boundaries to resize columns. You can also drag a column to a new
position.
• Tables are implemented by the JTable class, which extends JComponent.
• Constructors
o JTable(Object data[ ][ ], Object colHeads[ ]):- Constructs a JTable to
display the values in the two dimensional array, rowData, with column names,
columnNames.
o JTable(int numRows, int numColumns):-Constructs a JTable with
numRows and numColumns of empty cells using DefaultTableModel.
• Here are the steps for using a table in an applet:
1. Create a JTable object.
2. Create a JScrollPane object.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane of the applet.
• 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.
This table has three columns. A two-dimensional array of strings is created for the
table cells. 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()
{
// Get content pane
Container contentPane = getContentPane();
// Set layout manager
contentPane.setLayout(new BorderLayout());
// Initialize column headings
final String[] colHeads = { "Name", "Roll No", "Address", "Percentage" };
// Initialize data
final Object[][] data = {
{ "Ramesh Shetty","1","kalina","67%" },
{ "Kapil Varma","2","bandra","45%" },
{ "Ritu Singh", "3","malad","56%" },
{ "Amita Jadhav","4","miraroad","89%" },
{ "Sumit Sahani", "5","mahim","79%" },
1.14 Trees
• One of Swing's advanced components is JTree. Trees are good for representing
hierarchical information, like the contents of a disk drive or a company's
organizational chart.
• The classes that support JTree have their own package, javax.swing.tree.
• A tree's data model is made up of interconnected nodes. A node has a name, typically,
a parent, and some number of children (possibly 0).
• In Swing, a node is represented by the TreeNode interface. Nodes that can be
modified are represented by MutableTreeNode. A concrete implementation of this
interface is DefaultMutableTreeNode. One node, called the root node, usually
resides at the top of the hierarchy.
• A tree's data model is represented by the TreeModel interface. Swing provides an
implementation of this interface called DefaultTreeModel. You can create a
DefaultTreeModel by passing a root TreeNode to its constructor.
• You could create a TreeMdel with just one node like this:
TreeNode root = new DefaultMutableTreeNode("Root node");
TreeModel model = new DefaultTreeModel(root);
• Here's another example with a real hierarchy. The root node contains two nodes,
Node 1 and Group. The Group node contains Node 2 and Node 3 as sub nodes.
MutableTreeNode root = new DefaultMutableTreeNode("Root node");
MutableTreeNode group = new DefaultMutableTreeNode("Group");
root.insert(group, 0);
root.insert(new DefaultMutableTreeNode("Node 1"), 1);
group.insert (new DefaultMutableTreeNode("Node 2"), 0);
group.insert (new DefaultMutableTreeNode("Node 3"), 1);
• The second parameter to the insert() method is the index of the node in the parent.
Once you've got your nodes organized, you can create a TreeModel in the same way
as before:
Tree Events
A tree fires several events. You can find out when nodes have been expanded and
collapsed, and when selections occur. Two distinct event listener interfaces
handle this information.
TreeExpansionListener
TreeSelectionListener
• The following example registers an event listener that prints out the last selected
node:
tree.addTreeSelectionListener(new TreeSelectionListener( ) {
public void valueChanged(TreeSelectionEvent e) {
TreePath tp = e.getNewLeadSelectionPath( );
System.out.println(tp.getLastPathComponent( ));
}
});
• Constructors:-
o JTree():-Returns a JTree with a sample model.
o JTree(TreeModel newModel):-Returns an instance of JTree which displays
the root node -- the tree is created using the specified data model.
o JTree(TreeNode root):-Returns a JTree with the specified TreeNode as its
root, which displays the root node.
o 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.
• Interfaces associated with the trees are:-
o MutableTreeNode:-Defines the requirements for a tree node object that can
change -- by adding or removing child nodes, or by changing the contents of a
user object stored in the node.
• Event class:-
o TreeExpansionEvent:-An event used to identify a single path in a tree. The
source returned by getSource will be an instance of JTree.
• Other Classes associated with the trees are:-
o DefaultMutableTreeNode :-DefaultMutableTreeNode implements the
MutableTreeNode interface A DefaultMutableTreeNode is a general-purpose
node in a tree data structure. A tree node may have at most one parent and 0 or
more children. DefaultMutableTreeNode provides operations for examining
and modifying a node's parent and children and also operations for examining
the tree that the node is a part of.
o TreeModel:- A simple tree data model that uses TreeNodes
o TreePath:- Represents a path to a node. A TreePath is an array of Objects
that are taken from a TreeModel. The elements of the array are ordered such
that the root is always the first element (index 0) of the array.
• This section contains an example that showcases the following tree techniques:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
JList
• JList is a component that allows the user to select one or more objects from a list. A
separate model, ListModel, represents the contents of the list.
• It's easy to display an array or vector of objects, using a JList constructor that builds a
ListModel instance for you.
• Build JList:
o Create a JList that displays the strings in data[]
• JList doesn't support scrolling directly. To create a scrolling list you make the JList
the viewport view of a JScrollPane. For example:
// Imports
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
• Items can be drawn differently depending on whether or not they are selected,
including the foreground and background colors and the font.
• This example shown here displays selected item in a 24-point font and
changes the background color of the selection to red.
• This example includes images for each item to help the user better identify the
style associated with each selection, greatly improving the user experience
with this application.
• Additionally, this method assigns the correct image to the item being drawn.
• That the above example extended a JLabel class to custom render the list items.
Other components can be used in place of the JLabel ranging JButton, JCheckBox
through to JTextArea.
• The code listing for the RenderListExample.java class is as follows:
// Imports
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class RenderListExample
extends JFrame
{
// Instance attributes used in this example
private JPanel topPanel;
private JList listbox;
// Imports
import java.awt.*;
import javax.swing.*;
import javax.swing.ListCellRenderer.*;
public CustomCellRenderer()
{
setOpaque(true);
return this;
}
}
Interface used:-
• ListCellRenderer:-
o Identifies components that can be used as "rubber stamps" to paint the
cells in a JList.
o For example, to use a JLabel as a ListCellRenderer, you would write
something like this:
class MyCellRenderer extends JLabel implements ListCellRenderer {
public MyCellRenderer() {
setOpaque(true);
}
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
setText(value.toString());
setBackground(isSelected ? Color.red : Color.white);
setForeground(isSelected ? Color.white : Color.black);
return this;
}
}
Methods Used:-