Ajava Module3 - Notes
Ajava Module3 - Notes
Module 3
Introducing Swing: The Origin of Swing, Swing Is Built on AWT, Two Key Swing Features, The MVC
Connection, Components and Containers, The Swing Packages, A Simple Swing Application, Event Handling,
Painting in Swing, Exploring Swing : JLabel and ImageIcon, JTextField,The Swing Buttons-JButton,
JToggleButton, Check Boxes, Radio Buttons
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit
[AWT]. Java Swing offers much-improved functionality over AWT, new components, expanded
components features, and excellent event handling with drag-and-drop support.
Swing has about four times the number of User Interface [UI] components as AWT and is part of the
standard Java distribution. By today’s application GUI requirements, AWT is a limited
implementation, not quite capable of providing the components required for developing complex GUIs
required in modern commercial applications. The AWT component set has quite a few bugs and does
take up a lot of system resources when compared to equivalent Swing resources. Netscape introduced
its Internet Foundation Classes [IFC] library for use with Java. Its Classes became very popular with
programmers creating GUI’s for commercial applications.
Includes New and improved Components that have been enhancing the looks and Functionality of
GUIs’
Swing can be used to build (Develop) The Standalone swing GUI Apps as Servlets and Applets
Swing is more portable and more flexible than AWT, the Swing is built on top of the AWT.
Java Swing Components are Platform-independent, and The Swing Components are lightweight.
Swing Supports a Pluggable look and feel and Swing provides more powerful components.
Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight component
development. For a component to qualify as lightweight, it must not depend on any non-Java [O/s
based) system classes. Swing components have their own view supported by Java’s look and feel
classes.
Pluggable Look and Feel: This feature enable the user to switch the look and feel of Swing
components without restarting an application. The Swing library supports components’ look and feels
that remain the same across all platforms wherever the program runs. The Swing library provides an
API that gives real flexibility in determining the look and feel of the GUI of an application
Highly customizable – Swing controls can be customized in a very easy way as visual appearance is
independent of internal representation.
Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane, slider,
colorpicker, and table controls.
1. The way that the component looks when rendered on the screen.
Over the years, one component architecture has proven itself to be exceptionally effective: – Model-
View-Controller or MVC for short.
In MVC terminology, the model corresponds to the state information associated with the Component.
The view determines how the component is displayed on the screen, including any aspects of the view
that are affected by the current state of the model.
A Swing GUI consists of two key items: components and containers. However, this distinction is mostly
conceptual because all containers are also components. The difference between the two is found in their
intended purpose: As the term is commonly used, a component is an independent visual control, such as a
push button or slider. A container holds a group of components. Thus, a container is a special type of
component that is designed to hold other components. Furthermore, in order for a component to be displayed,
it must be held within a container. Thus, all Swing GUIs will have at least one container. Because containers
are components, a container can also hold other containers. This enables Swing to define what is called a
containment hierarchy, at the top of which must be a top-level container.
Components
In general, Swing components are derived from the JComponent class. (The only exceptions to this are the
four top-level containers, described in the next section.) JComponent provides the functionality that is
common to all components. For example, JComponent supports the pluggable look and
feel. JComponent inherits the AWT classes Container and Component.
Swing is a very large subsystem and makes use of many packages. At the time of this writing, these are the
packages defined by Swing.
javax.swing
javax.swing.border
javax.swing.colorchooser
javax.swing.event
javax.swing.filechooser
javax.swing.plaf
javax.swing.plaf.basic
javax.swing.plaf.metal
javax.swing.plaf.multi
javax.swing.plaf.nimbus
javax.swing.plaf.synth
javax.swing.table
javax.swing.text
javax.swing.text.html
javax.swing.text.html.parser
javax.swing.text.rtf
javax.swing.tree
javax.swing.undo
The main package is javax.swing. This package must be imported into any program that uses Swing. It
contains the classes that implement the basic Swing components, such as push buttons, labels, and check
boxes.
Import Statements:
javax.swing.*: Contains essential Swing components like JFrame, JButton, JLabel, and JTextField.
java.awt.event.*: Provides classes for handling events like button clicks.
JFrame: The main container that holds the GUI components. We set its size, close operation, and layout.
JLabel: A simple component to display static text like instructions.
JTextField: A single-line input field for the user to enter text.
JButton: A clickable button that triggers an action.
ActionListener: An interface used to respond to events. We implement its actionPerformed method to define what
happens when the button is clicked.
Event Handling:
e.getSource(): Identifies the component that triggered the event.
Dept. of CSE, BIT Page 5
Introducing Swing ((Module-3)
textField.getText(): Fetches the user’s input from the text field
Event Handling
The preceding example showed the basic form of a Swing program, but it left out one important part: event handling.
Because JLabel does not take input from the user, it does not generate events, so no event handling was needed.
However, the other Swing components do respond to user input and the events generated by those interactions need to
be handled. Events can also be generated in ways not directly related to user input. For example, an event is generated
when a timer goes off. Whatever the case, event handling is a large part of any Swing-based application.
The event handling mechanism used by Swing is the same as that used by the AWT. This approach is called
the delegation event model. In many cases, Swing uses the same events as does the AWT, and these events are
packaged in java.awt.event. Events specific to Swing are stored in javax.swing.event.
Although events are handled in Swing in the same way as they are with the AWT, it is still useful to work through a
simple example. The following program handles the event generated by a Swing push button. Sample output is shown
in Figure 31-2.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbtnAlpha.addActionListener(new ActionListener() {
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) { jlab.setText("Beta was pressed.");
}
});
jfrm.add(jbtnAlpha); jfrm.add(jbtnBeta);
jfrm.add(jlab);
//Display the frame.
jfrm.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() { new EventDemo();
}
});
}
}
First, notice that the program now imports both the java.awt and java.awt.event packages. The java.awt package is
needed because it contains the FlowLayout class, which supports the standard flow layout manager used to lay out
components in a frame. (See Chapter 26 for coverage of layout managers.) The java.awt.event package is needed
because it defines the ActionListener interface and the ActionEvent class.
The EventDemo constructor begins by creating a JFrame called jfrm. It then sets the layout manager for the content
pane of jfrm to FlowLayout. Recall that, by default, the content pane uses BorderLayout as its layout manager.
However, for this example, FlowLayout is more convenient. Notice that FlowLayout is assigned using this
statement:
jfrm.setLayout(new FlowLayout());
As explained, in the past you had to explicitly call getContentPane( ) to set the layout manager for the content pane.
This requirement was removed as of JDK 5.
After setting the size and default close operation, EventDemo( ) creates two push buttons, as shown here:
The first button will contain the text "Alpha" and the second will contain the text "Beta". Swing push buttons are
instances of JButton. JButton supplies several constructors. The one used here is
JButton(String msg)
The msg parameter specifies the string that will be displayed inside the button.
When a push button is pressed, it generates an ActionEvent. Thus, JButton provides the addActionListener(
) method, which is used to add an action listener. (JButton also provides removeActionListener( ) to remove a
listener, but this method is not used by the program.) As explained in Chapter 24, the ActionListener interface
defines only one method: actionPerformed( ). It is shown again here for your convenience:
This method is called when a button is pressed. In other words, it is the event handler that is called when a button
press event has occurred.
Next, event listeners for the button’s action events are added by the code shown here:
// Add action listener for Alpha.
jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Alpha was pressed.");
});
// Add action listener for Beta.
jbtnBeta.addActionListener(new ActionListener() {
});
Here, anonymous inner classes are used to provide the event handlers for the two buttons. Each time a button is
pressed, the string displayed in jlab is changed to reflect which button was pressed.
Beginning with JDK 8, lambda expressions can also be used to implement event handlers. For example, the event
handler for the Alpha button could be written like this:
As you can see, this code is shorter. For the benefit of readers using versions of Java prior to JDK 8, subsequent
examples will not use lambda expressions, but you should consider using them for new code that you create.
jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);
Dept. of CSE, BIT Page 8
Introducing Swing ((Module-3)
Finally, jlab is added to the content pane and window is made visible. When you run the program, each time you
press a button, a message is displayed in the label that indicates which button was pressed.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Create a label
label = new JLabel("Enter your name: ");
add(label); // Add the label to the applet
// Create a button
button = new JButton("Greet");
add(button); // Add the button to the applet
<html>
<body>
<applet code="SimpleSwingApplet.class" width="400"
height="200"></applet>
</body>
</html>
Running the Applet:
To run the applet, you can use an applet viewer or embed it in an HTML file. Here’s how:
Step 1: Save as SimpleSwingApplet.java and Compile
javac SimpleSwingApplet.java
Step 3: Run with Applet Viewer
Use the applet viewer to run the applet:
appletviewer SimpleSwingApplet.html
Painting Fundamentals
The AWT class Component defines a method called paint( ) that is used to draw output directly to the surface
of a component. For the most part, paint( ) is not called by your program. (In fact, only in the most unusual
cases should it ever be called by your program.) Rather, paint( ) is called by the run-time system whenever a
component must be rendered. This situation can occur for several reasons. For example, the window in which
the component is displayed can be overwritten by another window and then uncovered. Or, the window might
be minimized and then restored. The paint( ) method is also called when a program begins running. When
writing AWT-based code, an application will override paint( ) when it needs to write output directly to the
surface of the component.
To paint to the surface of a Swing component, you will create a subclass of the component and then
override its paintComponent( ) method.
To cause a component to be painted under program control, call repaint( ). It works in Swing just as
it does for the AWT. The repaint( ) method is defined by Component.
When drawing to the surface of a component, you must be careful to restrict your output to
the area that is inside the border.
This is the area defined by the current size of the component minus the space used by the
border. Therefore, before you paint to a component, you must obtain the width of the border
and then adjust your drawing accordingly.
To obtain the border width, call getInsets( ), shown here: Insets getInsets( )
This method is defined by Container and overridden by JComponent. It returns an Insets object
that contains the dimensions of the border. The inset values can be obtained by using these fields:
int top; int bottom; int left;
int right;
By subtracting the value of the insets, you can compute the usable width and height of the
component.
A Paint Example
import java.awt.*;
import javax.swing.*;
4. Drawing a Rectangle
g.setColor(Color.RED);
g.fillRect(50, 50, 100, 100);
g.setColor(Color.RED): Sets the drawing color to red.
g.fillRect(50, 50, 100, 100): Draws a filled rectangle at coordinates (50, 50) with a width of 100 and height
of 100 pixels.
g.setColor(Color.BLUE);
g.fillOval(200, 50, 100, 100);
g.setColor(Color.BLUE): Sets the drawing color to blue.
g.fillOval(200, 50, 100, 100): Draws a filled oval inside a bounding box starting at (200, 50) with a width
and height of 100 pixels. Since the width and height are equal, this oval appears as a circle.
Exploring Swing
The Swing component classes described in this chapter are shown here:
JButton
JList
JTable
JCheckBox
JRadioButton
JTextField
JComboBox
JScrollPane
JToggleButton
JLabel
JTabbedPane
JTree
These components are all lightweight, which means that they are all derived from
JComponent.
Also discussed is the ButtonGroup class, which encapsulates a mutually exclusive set of Swing buttons, and
ImageIcon, which encapsulates a graphics image. Both are defined by Swing and packaged in
javax.swing.
ImageIcon(String filename)
The icon and text associated with the label can be obtained by the following methods:
The icon and text associated with a label can be set by these methods:
Here, icon and str are the icon and text, respectively. Therefore, using setText( ) it is possible to change the
text inside a label during program execution.
The following applet illustrates how to create and display a label containing both an icon and a string. It begins
by creating an ImageIcon object for the file hourglass.png, which depicts an hourglass. This is used
Dept. of CSE, BIT Page 15
Introducing Swing ((Module-3)
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 javax.swing.*;
import java.awt.*;
JTextField
JTextField is the simplest Swing text component. It is also probably its most widely used
text component. JTextField allows you to edit one line of text. It is derived from JTextComponent, which
provides the basic functionality common to Swing text components. JTextField uses
the Document interface for its model. Three of JTextField’s constructors are shown here:
Here, str is the string to be initially presented, and cols is the number of columns in the text field. If no
string is specified, the text field is initially empty. If the number of columns is not specified, the text field is
sized to fit the specified string.
Dept. of CSE, BIT Page 16
Introducing Swing ((Module-3)
JTextField generates events in response to user interaction. For example, an ActionEvent is fired when the
user presses enter. A CaretEvent is fired each time the caret (i.e., the cursor) changes position.
(CaretEvent is packaged in javax.swing.event.) Other events are also possible. In many cases, your
program will not need to handle these events. Instead, you will simply obtain the string currently in the text
field when it is needed. To obtain the text currently in the text field, call getText( ).
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Create a JTextField
JTextField textField = new JTextField(20); // 20 columns wide
// Create a JButton
JButton button = new JButton("Show Text");
AbstractButton contains many methods that allow you to control the behavior of buttons. For example, you
can define different icons that are displayed for the button 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 a button. The
following methods set these icons:
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 the indicated purpose.
The text associated with a button can be read and written via the following methods:
String getText( )
The model used by all buttons is defined by the ButtonModel interface. A button generates an action event
when it is pressed. Other events are possible. Each of the concrete button classes is examined next.
JButton
The JButton class provides the functionality of a push button. You have already seen a simple form of it in
the preceding chapter. JButton allows an icon, a string, or both to be associated with the push button. Three
of its constructors are shown here:
When the button is pressed, an ActionEvent is generated. Using the ActionEvent object passed to
the actionPerformed( ) method of the registered ActionListener, you can obtain the action
command string associated with the button. By default, this is the string displayed inside the button.
However, you can set the action command by calling setActionCommand( ) on the button. You can obtain
the action command by calling getActionCommand( ) on the event object. It is declared like this:
String getActionCommand( )
The action command identifies the button. Thus, when using two or more buttons within the same
application, the action command gives you an easy way to determine which button was pressed.
In the preceding chapter, you saw an example of a text-based button. The following demonstrates an icon-
based button. It displays four push buttons and a label. Each button displays an icon that represents a
timepiece. When a button is pressed, the name of that timepiece is displayed in the label.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Create a JLabel
JLabel label = new JLabel("Click the button");
// Create a JButton
JButton button = new JButton("Click Me");
JToggleButton
A useful variation on the push button is called a toggle button. A toggle button looks just like a push button,
but it acts differently because it has two states: pushed and released. That is, when you press a toggle button,
it stays pressed rather than popping back up as a regular push button does. When you press the toggle button
a second time, it releases (pops up). Therefore, each time a toggle button is pushed, it toggles between its
two states.
Toggle buttons are objects of the JToggleButton class. JToggleButton implements AbstractButton. In
addition to creating standard toggle buttons, JToggleButton is a superclass for two other Swing
components that also represent two-state controls. These are JCheckBox and JRadioButton, which are
described later in this chapter. Thus, JToggleButton defines the basic functionality of all two-state
components.
JToggleButton defines several constructors. The one used by the example in this section is shown here:
JToggleButton(String str)
This creates a toggle button that contains the text passed in str. By default, the button is in the off position.
Other constructors enable you to create toggle buttons that contain images, or images and text.
Object getItem( )
Here is an example that uses a toggle button. Notice how the item listener works. It simply calls isSelected(
) to determine the button’s state.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
// Create a JToggleButton
JToggleButton toggleButton = new JToggleButton("OFF");
// Create a JLabel
JLabel label = new JLabel("Button is OFF");
Check Boxes
The JCheckBox class provides the functionality of a check box. Its immediate superclass
is JToggleButton, which provides support for two-state buttons, as just described. JCheckBox defines
several constructors. The one used here is
JCheckBox(String str)
It creates a check box that has the text specified by str as a label. Other constructors let you specify the
initial selection state of the button and specify an icon.
When the user selects or deselects a check box, an ItemEvent is generated. You can obtain a reference to
the JCheckBox that generated the event by calling getItem( ) on the
ItemEvent passed to the itemStateChanged( ) method defined by ItemListener. The easiest way to
determine the selected state of a check box is to call isSelected( ) on the JCheckBox instance.
The following example illustrates check boxes. It displays four check boxes and a label. When the user
clicks a check box, an ItemEvent is generated. Inside the itemStateChanged( ) method, getItem( ) is
called to obtain a reference to the JCheckBox object that generated the event. Next, a call to isSelected(
) determines if the box was selected or cleared. The getText( ) method gets the text for that check box and
uses it to set the text inside the label.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Create a JLabel
JLabel label = new JLabel("Select your favorite programming languages:");
// Create JCheckBoxes
JCheckBox cbC = new JCheckBox("C");
JCheckBox cbCpp = new JCheckBox("C++");
JCheckBox cbJava = new JCheckBox("Java");
JCheckBox cbPython = new JCheckBox("Python");
// Create a JButton
JButton submitButton = new JButton("Submit");
Radio Buttons
Radio buttons are a group of mutually exclusive buttons, in which only one button can be
selected at any one time. They are supported by the JRadioButton class, which extends
JToggleButton. JRadioButton provides several constructors. The one used in the example is
shown here:
JRadioButton(String str)
Here, str is the label for the button. Other constructors let you specify the initial selection state
of the button and specify an icon.
In order for their mutually exclusive nature to be activated, radio buttons must be configured
into a group. Only one of the buttons in the 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. A button group is created by the ButtonGroup class. Its default
constructor is invoked for this purpose. Elements are
then added to the button group via the following method: void add(AbstractButton ab)
A JRadioButton generates action events, item events, and change events each time the button
selection changes. Most often, it is the action event that is handled, which means that you will
normally implement the ActionListener interface. Recall that the only method defined by
ActionListener is actionPerformed( ). Inside this method, you can use a number of
different ways to determine which button was selected. First, you can check its action
command by calling getActionCommand( ). By default, the action command is the same as
the button label, but you can set the action command to something else by calling
setActionCommand( ) on the radio button. Second, you can call getSource( ) on the
ActionEvent object and check that reference against the buttons. Third, you can check each
radio button to find out which one is currently selected by calling isSelected( ) on each button.
Finally, each button could use its own action event handler implemented as either an
anonymous inner class or a lambda expression. Remember, each time an action event occurs,
it means that the button being selected has changed and that one and only one button will be
selected.
The following example illustrates how to use radio buttons. Three radio buttons are created.
The buttons are then added to a button group. As explained, this is necessary to cause their
mutually exclusive behavior. Pressing a radio button generates an action event, which is
handled by actionPerformed( ). Within that handler, the getActionCommand( ) method gets
the text that is associated with the radio button and uses it to set the text within a label.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Create a JLabel
JLabel label = new JLabel("Select your gender:");
// Create JRadioButtons
JRadioButton rbMale = new JRadioButton("Male");
JRadioButton rbFemale = new JRadioButton("Female");
JRadioButton rbOther = new JRadioButton("Other");
// Create a ButtonGroup to group radio buttons (so only one can be selected at a time)
ButtonGroup group = new ButtonGroup();
group.add(rbMale);
group.add(rbFemale);
group.add(rbOther);