0% found this document useful (0 votes)
3 views27 pages

Ajava Module3 - Notes

Module 3 introduces Java Swing, an extension of AWT that provides enhanced functionality for building graphical user interfaces (GUIs) with a rich set of components. Key features include a pluggable look and feel, lightweight components, and the use of the Model-View-Controller (MVC) architecture. The document also covers event handling, the structure of Swing applications, and provides examples of simple Swing applications.

Uploaded by

Sneha Raju
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)
3 views27 pages

Ajava Module3 - Notes

Module 3 introduces Java Swing, an extension of AWT that provides enhanced functionality for building graphical user interfaces (GUIs) with a rich set of components. Key features include a pluggable look and feel, lightweight components, and the use of the Model-View-Controller (MVC) architecture. The document also covers event handling, the structure of Swing applications, and provides examples of simple Swing applications.

Uploaded by

Sneha Raju
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/ 27

Introducing Swing ((Module-3)

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

 Introduction to Java Swing

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.

 Swing is a Set of API (API- Set of Classes and Interfaces)

 Swing is Provided to Design Graphical User Interfaces

 Swing is an Extension library to the AWT (Abstract Window Toolkit)

 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

 It Employs model/view design architecture.

 Swing is more portable and more flexible than AWT, the Swing is built on top of the AWT.

 Swing is Entirely written in Java.

 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.

 such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.

 Further Swing Follows MVC.

Dept. of CSE,BIT Page 1


GAT
Introducing Swing ((Module-3)
Features Of Swing Class

 Pluggable look and feel.


 Uses MVC architecture.
 Lightweight Components
 Platform Independent
 Advanced features such as JTable, JTabbedPane, JScollPane, etc.
 Java is a platform-independent language and runs on any client machine, the GUI look and feel, owned
and delivered by a platform-specific O/S, simply does not affect an application’s GUI constructed
using Swing 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. 

The MVC Connection

 In general, a visual component is a composite of three distinct aspects:

1. The way that the component looks when rendered on the screen.

2. The way such that the component reacts to the user.

3. The state information associated with the component.

 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. 

 The controller determines how the component reacts to the user.

Dept. of CSE,BIT Page 2


GAT
Introducing Swing ((Module-3)
Components and Containers

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.

Thus, a Swing component is built on and compatible with an AWT component.

Dept. of CSE,BIT Page 3


GAT
Introducing Swing ((Module-3)

The Swing Packages

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.

A Simple Swing Application


// Import necessary Swing and AWT packages
import javax.swing.*; // Contains classes for building the GUI (JFrame, JButton, JLabel, etc.)
import java.awt.event.ActionEvent; // Used for handling button click events
import java.awt.event.ActionListener; // Provides an interface for listening to events

public class SimpleSwingAppWithExplanations {


public static void main(String[] args) {

// Step 1: Create the main window (JFrame)


JFrame frame = new JFrame("Simple Swing Application"); // Create a new window with the title "Simple Swing
Application"
frame.setSize(400, 200); // Set the width to 400 pixels and the height to 200 pixels
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Ensure the application closes when the window
is closed
frame.setLayout(null); // Use absolute positioning for components (no layout manager)

Dept. of CSE,BIT Page 4


GAT
Introducing Swing ((Module-3)

// Step 2: Add a JLabel to display instructions


JLabel label = new JLabel("Enter your name:"); // Create a label with text to prompt the user
label.setBounds(50, 30, 120, 25); // Set the position (x, y) and size (width, height) of the label
frame.add(label); // Add the label to the frame

// Step 3: Add a JTextField for user input


JTextField textField = new JTextField(); // Create a text field where the user can enter their name
textField.setBounds(180, 30, 150, 25); // Set the position and size of the text field
frame.add(textField); // Add the text field to the frame

// Step 4: Add a JButton to perform an action


JButton button = new JButton("Show Message"); // Create a button with the label "Show Message"
button.setBounds(50, 80, 150, 30); // Set the position and size of the button
frame.add(button); // Add the button to the frame

// Step 5: Add a JLabel to display the output message


JLabel messageLabel = new JLabel(""); // Create an empty label to display the output message
messageLabel.setBounds(50, 120, 300, 25); // Set the position and size of the label
frame.add(messageLabel); // Add the label to the frame

// Step 6: Add an ActionListener to the button


button.addActionListener(new ActionListener() { // Add a listener to handle button clicks
public void actionPerformed(ActionEvent e) { // This method is called when the button is clicked
String name = textField.getText(); // Get the text entered by the user in the text field
if (!name.isEmpty()) { // Check if the user has entered something
messageLabel.setText("Hello, " + name + "!"); // Display a greeting with the entered name
} else { // If no text is entered
messageLabel.setText("Please enter your name."); // Prompt the user to enter a name
}
}
});

// Step 7: Make the frame visible


frame.setVisible(true); // Show the frame and make it ready for user interaction
}
}

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

 messageLabel.setText(): Updates the text displayed in the label.


frame.setVisible(true): Makes the GUI window visible to the user.

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.

// Handle an event in a Swing program.


import java.awt.*; import java.awt.event.*; import javax.swing.*;
class EventDemo {
JLabel jlab;
EventDemo() {

// Create a new JFrame container.


JFrame jfrm = new JFrame("An Event Example");

//Specify FlowLayout for the layout manager.


jfrm.setLayout(new FlowLayout());

//Give the frame an initial size.


jfrm.setSize(220, 90);

//Terminate the program when the user closes the application.

jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Make two buttons.


JButton jbtnAlpha = new JButton("Alpha");
JButton jbtnBeta = new JButton("Beta");

Dept. of CSE, BIT Page 6


Introducing Swing ((Module-3)

//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() {
public void actionPerformed(ActionEvent ae) { jlab.setText("Beta was pressed.");
}
});

//Add the buttons to the content pane.

jfrm.add(jbtnAlpha); jfrm.add(jbtnBeta);

//Create a text-based label.


jlab = new JLabel("Press a button.");

//Add the label to the content pane.

jfrm.add(jlab);
//Display the frame.
jfrm.setVisible(true);
}
public static void main(String args[]) {

// Create the frame on the event dispatching thread.

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:

JButton jbtnAlpha = new JButton("Alpha");


Dept. of CSE, BIT Page 7
Introducing Swing ((Module-3)

JButton jbtnBeta = new JButton("Beta");

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:

void actionPerformed(ActionEvent ae)

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() {

public void actionPerformed(ActionEvent ae) { jlab.setText("Beta was pressed.");

});

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:

jbtnAlpha.addActionListener( (ae) -> jlab.setText("Alpha was pressed."));

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.

Next, the buttons are added to the content pane of jfrm:

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.

Create a Swing Applet


The second type of program that commonly uses Swing is the applet. Swing-based applets are similar to
AWT-based applets, but with an important difference: A Swing applet extends JApplet rather than Applet.
JApplet is derived from Applet. Thus, JApplet includes all of the functionality found in Applet and adds
support for Swing. JApplet is a top-level Swing container, which means that it is not derived from
JComponent. Because JApplet is a top-level container, it includes the various panes described earlier. This
means that all components are added to JApplet’s content pane in the same way that components are added
to JFrame’s content pane.
Swing applets use the same four life-cycle methods as described in Chapter 23: init( ), start( ), stop( ), and
destroy( ). Of course, you need override only those methods that are needed by your applet. Painting is
accomplished differently in Swing than it is in the AWT, and a Swing applet will not normally override the
paint( ) method.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

// A simple Swing-based applet


public class SimpleSwingApplet extends JApplet {

private JLabel label;


private JTextField textField;
private JButton button;

// This method is called when the applet is initialized

public void init() {


// Set the layout of the applet
setLayout(new FlowLayout()); // Use FlowLayout for arranging components

// Create a label
label = new JLabel("Enter your name: ");
add(label); // Add the label to the applet

// Create a text field


textField = new JTextField(15); // Text field with 15 columns
add(textField); // Add the text field to the applet

// Create a button
button = new JButton("Greet");
add(button); // Add the button to the applet

Dept. of CSE, BIT Page 9


Introducing Swing ((Module-3)
// Create an action listener for the button
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Get the text entered in the text field
String name = textField.getText();
if (!name.isEmpty()) {
// Display a greeting message in a dialog box
JOptionPane.showMessageDialog(SimpleSwingApplet.this, "Hello, " + name + "!");
} else {
// Display an error message if the text field is empty
JOptionPane.showMessageDialog(SimpleSwingApplet.this, "Please enter your name.");
}
}
});
}
}
JApplet:
 This is the base class for Swing-based applets. It extends Applet and provides support for Swing
components.
init():
 The init method is called by the browser or applet viewer to initialize the applet. It is similar to the
main method in regular Java applications. 
Swing Components:
 JLabel: Displays static text.
 JTextField: Allows the user to input text.
 JButton: A clickable button.
Layout Manager:
 FlowLayout: Places components in a row, wrapping to the next row as needed.
Event Handling:
 An ActionListener is added to the button to handle click events. The actionPerformed method is
triggered when the button is clicked. 
Dialogs:
 JOptionPane.showMessageDialog: Displays a message dialog box

<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

Dept. of CSE, BIT Page 10


Introducing Swing ((Module-3)
Painting in Swing
Although the Swing component set is quite powerful, you are not limited to using it because Swing also lets
you write directly into the display area of a frame, panel, or one of Swing’s other components, such as JLabel.
Although many (perhaps most) uses of Swing will not involve drawing directly to the surface of a component,
it is available for those applications that need this capability. To write output directly to the surface of a
component, you will use one or more drawing methods defined by the AWT, such as drawLine(
) or drawRect( ).

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.

 The paintComponent( ) method is shown here:


protected void paintComponent(Graphics g)
The parameter g is the graphics context to which output is written.

 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.

Compute the Paintable Area

 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;

Dept. of CSE, BIT Page 11


Introducing Swing ((Module-3)
 These values are then used to compute the drawing area given the width and the height of the
component. You can obtain the width and height of the component by calling getWidth(
) and getHeight( ) on the component. They are shown here:

int getWidth( ) int getHeight( )

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.*;

public class onePaint extends JPanel {


@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

// Set color and draw a rectangle


g.setColor(Color.RED);
g.fillRect(50, 50, 100, 100);

// Set color and draw a circle


g.setColor(Color.BLUE);
g.fillOval(200, 50, 100, 100);
}

public static void main(String[] args) {


JFrame frame = new JFrame("Simple Paint Example");
onePaint panel = new onePaint();

Dept. of CSE, BIT Page 12


Introducing Swing ((Module-3)
frame.add(panel);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
1. Importing Required Packages
import javax.swing.*;
import java.awt.*;
 javax.swing.*: This package provides classes for building graphical user interfaces (GUIs) in Java.
 java.awt.*: This package contains classes for handling graphics, colors, and basic UI components.

2. Defining the PaintExample Class

public class PaintExample extends JPanel {


 The class PaintExample extends JPanel, meaning it inherits properties of a JPanel and can be used as a
drawable component in a JFrame. 
 By extending JPanel, we can override the paintComponent() method to draw custom shapes.

3. Overriding paintComponent() Method


@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
 paintComponent(Graphics g): This method is automatically called whenever the panel needs to be redrawn.
 super.paintComponent(g): Ensures that the parent class (JPanel) properly clears and repaints the background
before drawing new content.

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. 

5. Drawing a Circle (Oval)

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.

6. Creating the JFrame (Main Method)

public static void main(String[] args) {


JFrame frame = new JFrame("Simple Paint Example");
PaintExample panel = new PaintExample();
 A new window (JFrame) is created with the title "Simple Paint Example".
 An instance of PaintExample (the custom JPanel with drawings) is created.

7. Adding the Panel to the Frame


frame.add(panel);
 The custom JPanel (PaintExample) is added to the JFrame so it can be displayed. 
Dept. of CSE, BIT Page 13
Introducing Swing ((Module-3)

8. Setting Frame Properties


frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
 frame.setSize(400, 300): Sets the window size to 400 pixels width and 300 pixels height.
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures the program exits when the window is
closed.
 frame.setVisible(true): Makes the window visible.

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.

Dept. of CSE, BIT Page 14


Introducing Swing ((Module-3)
JLabel and ImageIcon - Swing
JLabel is Swing’s easiest-to-use component. It creates a label and was introduced in the preceding chapter.
Here, we will look at JLabel a bit more closely. JLabel can be used to display text and/or an icon. It is a
passive component in that it does not respond to user input. JLabel defines several constructors. Here are
three of them:
JLabel(Icon icon) JLabel(String str)
JLabel(String str, Icon icon, int align)
Here, str and icon are the text and icon used for the label. The align argument specifies the horizontal
alignment of the text and/or icon within the dimensions of the label. It must be one of the following
values: LEFT, RIGHT, CENTER, LEADING, or TRAILING. These constants are defined in
the SwingConstants interface, along with several others used by the Swing classes.
Notice that icons are specified by objects of type Icon, which is an interface defined by Swing. The easiest
way to obtain an icon is to use the ImageIcon class. ImageIcon implements Icon and encapsulates an
image. Thus, an object of type ImageIcon can be passed as an argument to the Icon parameter of JLabel’s
constructor. There are several ways to provide the image, including reading it from a file or downloading it
from a URL. Here is the ImageIcon constructor used by the example in this section:

ImageIcon(String filename)

It obtains the image in the file named filename.

The icon and text associated with the label can be obtained by the following methods:

Icon getIcon( ) String getText( )

The icon and text associated with a label can be set by these methods:

void setIcon(Icon icon) void setText(String str)

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.*;

public class JLabelImageExample {


public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("JLabel and ImageIcon Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout()); // Set layout

// Create a JLabel with text


JLabel textLabel = new JLabel("Hello, Swing!");

// Load an image and create an ImageIcon


ImageIcon icon = new ImageIcon("example.png"); // Ensure the image exists in the same directory

// Create a JLabel with the ImageIcon


JLabel imageLabel = new JLabel(icon);

// Add labels to the frame


frame.add(textLabel);
frame.add(imageLabel);

// Make the frame visible


frame.setVisible(true);
}
}

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:

JTextField(int cols) JTextField(String str, int cols) JTextField(String str)

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;

public class JTextFieldExample {


public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("JTextField Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// Create a JTextField
JTextField textField = new JTextField(20); // 20 columns wide

// Create a JLabel to display the input


JLabel label = new JLabel("Enter text and click the button");

// Create a JButton
JButton button = new JButton("Show Text");

// Add ActionListener to the button


button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText(); // Get text from JTextField
label.setText("You entered: " + text); // Update label

Dept. of CSE, BIT Page 17


Introducing Swing ((Module-3)
}
});

// Add components to the frame


frame.add(textField);
frame.add(button);
frame.add(label);

// Make the frame visible


frame.setVisible(true);
}
}

The Swing Buttons


Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and JRadioButton. All are
subclasses of the AbstractButton class, which extends JComponent. Thus, all buttons share a set of
common traits.

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( )

void setText(String str)

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

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:

JButton(Icon icon) JButton(String str) JButton(String str, Icon icon)

Dept. of CSE, BIT Page 18


Introducing Swing ((Module-3)
Here, str and icon are the string and icon used for the button.

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;

public class JButtonExample {


public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("JButton Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// Create a JLabel
JLabel label = new JLabel("Click the button");

// Create a JButton
JButton button = new JButton("Click Me");

// Add ActionListener to the button


button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText("Button Clicked!");
}
});

// Add components to the frame


frame.add(button);
frame.add(label);

Dept. of CSE, BIT Page 19


Introducing Swing ((Module-3)
// Make the frame visible
frame.setVisible(true);
}
}

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.

JToggleButton uses a model defined by a nested class called JToggleButton.Toggle-ButtonModel.


Normally, you won’t need to interact directly with the model to use a standard toggle button.
Like JButton, JToggleButton generates an action event each time it is pressed. Unlike JButton,
however, JToggleButton also generates an item event. This event is used by those components that support
the concept of selection. When a JToggleButton is pressed in, it is selected. When it is popped out, it is
deselected.
To handle item events, you must implement the ItemListener interface. Recall from Chapter 24, that each
time an item event is generated, it is passed to the itemStateChanged( ) method defined by ItemListener.
Inside itemStateChanged( ), the getItem( ) method can be called on the ItemEvent object to obtain a
reference to the JToggleButton instance that generated the event. It is shown here:

Object getItem( )

Dept. of CSE, BIT Page 20


Introducing Swing ((Module-3)
A reference to the button is returned. You will need to cast this reference to JToggleButton. The easiest
way to determine a toggle button’s state is by calling the isSelected( ) method
(inherited from AbstractButton) on the button that generated the event. It is shown here: boolean
isSelected( )

It returns true if the button is selected and false otherwise.

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;

public class JToggleButtonExample {


public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("JToggleButton Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// Create a JToggleButton
JToggleButton toggleButton = new JToggleButton("OFF");

// Create a JLabel
JLabel label = new JLabel("Button is OFF");

// Add ItemListener to the toggle button


toggleButton.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (toggleButton.isSelected()) {
toggleButton.setText("ON");
label.setText("Button is ON");
Dept. of CSE, BIT Page 21
Introducing Swing ((Module-3)
} else {
toggleButton.setText("OFF");
label.setText("Button is OFF");
}
}
});

// Add components to the frame


frame.add(toggleButton);
frame.add(label);

// Make the frame visible


frame.setVisible(true);
}
}

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.

Dept. of CSE, BIT Page 22


Introducing Swing ((Module-3)

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JCheckBoxExample {


public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("JCheckBox Example");
frame.setSize(300, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// 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");

// Create a JLabel to display the selected options


JLabel resultLabel = new JLabel("");

// Add ActionListener to the button


submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBuilder selectedLanguages = new StringBuilder("Selected: ");

Dept. of CSE, BIT Page 23


Introducing Swing ((Module-3)

if (cbC.isSelected()) selectedLanguages.append("C ");


if (cbCpp.isSelected()) selectedLanguages.append("C++ ");
if (cbJava.isSelected()) selectedLanguages.append("Java ");
if (cbPython.isSelected()) selectedLanguages.append("Python ");

// Update the result label


resultLabel.setText(selectedLanguages.toString());
}
});

// Add components to the frame


frame.add(label);
frame.add(cbC);
frame.add(cbCpp);
frame.add(cbJava);
frame.add(cbPython);
frame.add(submitButton);
frame.add(resultLabel);

// Make the frame visible


frame.setVisible(true);
}
}

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)

Dept. of CSE, BIT Page 24


Introducing Swing ((Module-3)
Here, ab is a reference to the button to be added to the group.

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;

public class JRadioButtonExample {


public static void main(String[] args) {
// Create a JFrame

Dept. of CSE, BIT Page 25


Introducing Swing ((Module-3)
JFrame frame = new JFrame("JRadioButton Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// 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);

// Create a Submit JButton


JButton submitButton = new JButton("Submit");

// Create a JLabel to display the selected option


JLabel resultLabel = new JLabel("");

// Add ActionListener to the button


submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedGender = "Selected: ";
if (rbMale.isSelected()) {
selectedGender += "Male";
} else if (rbFemale.isSelected()) {
selectedGender += "Female";
} else if (rbOther.isSelected()) {
selectedGender += "Other";
} else {
selectedGender += "None";
}

// Update the result label


resultLabel.setText(selectedGender);
}
});

// Add components to the frame


frame.add(label);
frame.add(rbMale);

Dept. of CSE, BIT Page 26


Introducing Swing ((Module-3)
frame.add(rbFemale);
frame.add(rbOther);
frame.add(submitButton);
frame.add(resultLabel);

// Make the frame visible


frame.setVisible(true);
}
}

Dept. of CSE, BIT Page 27

You might also like