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

Java Programming18

The document discusses Swing GUI programming in Java. It introduces key Swing components like JButton, JLabel, JTextField, JTextArea and how to add them to a JApplet. It covers layout management, event handling, and how to create simple Swing applications with these components. It also discusses checkboxes and radio buttons in Swing.

Uploaded by

preetham a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Java Programming18

The document discusses Swing GUI programming in Java. It introduces key Swing components like JButton, JLabel, JTextField, JTextArea and how to add them to a JApplet. It covers layout management, event handling, and how to create simple Swing applications with these components. It also discusses checkboxes and radio buttons in Swing.

Uploaded by

preetham a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

UNIT-V

GUI Programming with Swing –The AWT class hierarchy- introduction to swing- swing Vs
AWT- overview of some swing components –JButton-JLabel- JTextField-JTextArea- simple
applications- Layout management –Layout manager types –border- grid and flow
Event Handling: Events- Event sources- Event classes- Event Listeners- Delegation event
model- Example: handling mouse events- Adapter classes.

INTRODUCTION OF SWING

The Swing-related classes are contained in javax.swing and its subpackages, such
as javax.swing.tree. Many other Swing-related classes and interfaces exist that are
not examined in this chapter.
The remainder of this chapter examines various Swing components and
illustrates them through sample applets.

JApplet

Fundamental to Swing is the JApplet class, which extends Applet. Applets that
useSwing must be subclasses of JApplet. JApplet is rich with functionality that is notfound in
Applet. For example, JApplet supports various ―panes,‖heglass such pane, and the root pane. For the
examples in this chapter, we will not be using most of
JApplet’s enhanced features. However,AppletandJAppletoneis diffe important to this discussion,
because it is used by the sample applets in this chapter. 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.

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)

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.
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:
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 bothan 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:
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 you 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)

Here, s is the string to be presented, and cols is the number of columns in the text field.
The following example illustrates how to create a text field. The applet begins by getting its
content pane, and then a flow layout is assigned as its layout manager. Next, a JTextField object
is created and is added to the content pane.
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:
Buttons

Swing buttons provide features that are not found in the Button class defined by
theAWT. 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:


void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)

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)

Here, s is the text to be associated with the button.

Concrete subclasses of AbstractButton generate action events when they are pressed. Listeners
register and unregister for these events via the methods shown here:
void addActionListener(ActionListener al)
void removeActionListener(ActionListener al)
Here, al is the action listener.

AbstractButton is a superclass for push buttons, check boxes, and radio buttons.
Each is examined next.

The JButton Class

The JButton class provides the functionality of a push button. JButton allows an icon,a string,
or both to be associated with the push button. Some of its constructors are shown here:
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
Here, s and i are the string and icon used for the button.
Check Boxes

The JCheckBox class, which provides the functionality of a check box, is a concrete
implementation of AbstractButton. Its immediate superclass 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)

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: void setSelected(boolean state)
Here, state is true if the check box should be checked.
The following example illustrates how to create an applet that displays four checkboxes
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 itslayout
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 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());
}
}
Here is the output:

Radio Buttons

Radio buttons are supported by the JRadioButton class, which is a concrete implementation of
AbstractButton. Its immediate superclass 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)
Here, i is the icon for the button. The text is specified by s. If state is true, 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:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.

Radio button presses generate action events that are handled by actionPerformed( ).
The getActionCommand( ) method gets the text that is associated with a radio
button and uses it to set the text field.

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());
}
}
Output from this applet is shown here:

You might also like