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

Advanced Java Module-3

The document provides an overview of Swing, a GUI toolkit for Java that addresses limitations of the Abstract Window Toolkit (AWT) by introducing lightweight components and a pluggable look and feel. It explains the MVC architecture used in Swing, the distinction between components and containers, and the structure of a simple Swing application. The document also highlights key features and advantages of Swing, including its platform independence and richer functionality compared to AWT.

Uploaded by

rikise6992
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 views36 pages

Advanced Java Module-3

The document provides an overview of Swing, a GUI toolkit for Java that addresses limitations of the Abstract Window Toolkit (AWT) by introducing lightweight components and a pluggable look and feel. It explains the MVC architecture used in Swing, the distinction between components and containers, and the structure of a simple Swing application. The document also highlights key features and advantages of Swing, including its platform independence and richer functionality compared to AWT.

Uploaded by

rikise6992
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

Module-3

Introducing and Exploring


Swings
By:-
Dr. Vani V
Associate Professor
Dept. of ISE
BIT, Bangalore

Advanced Java (BIS402) 1


The Origins of Swing
• Swing did not exist in the early days of Java. Rather, it was a response to deficiencies present
in Java’s original GUI subsystem: the Abstract Window Toolkit.
• The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but
limited graphical interface.
• One reason for the limited nature of the AWT is that it translates its various visual components
into their corresponding, platform-specific equivalents, or peers. This means that the look and
feel of a component is defined by the platform, not by Java.
• Because the AWT components use native code resources, they are referred to as
heavyweight.

The use of native peers led to several problems.


• First, because of variations between operating systems, a component might look, or even act,
differently on different platforms. This potential variability threatened the philosophy of Java:
write once, run anywhere.
• Second, the look and feel of each component was fixed (because it is defined by the platform)
and could not be (easily) changed.
• Third, the use of heavyweight components caused some frustrating restrictions. For example, a
heavyweight component was always opaque.
• The solution was Swing. Introduced in 1997, Swing was included as part of the Java
Foundation Classes (JFC). Swing was initially available for use with Java 1.1 as a separate
library. However, beginning with Java 1.2, Swing (and the rest of the JFC) was fully integrated
into Java.

Advanced Java (BIS402) Dr. Vani V 2


Swing
SwingIsIsBuilt
Builton
onthe
theAWT
AWT
• Although Swing eliminates a number of the limitations inherent in the AWT, Swing does
not replace it. Instead, Swing is built on the foundation of the AWT. This is why the
AWT is still a crucial part of Java.
• Swing also uses the same event handling mechanism as the AWT. Therefore, a basic
understanding of the AWT and of event handling is required to use Swing.

Advanced Java (BIS402) Dr. Vani V 3


Two Key Swing Features
Swing was created to address the limitations present in the AWT. It does this through two key
features:

1. Swing Components Are Lightweight


• Swing components are lightweight. This means that they are written entirely in Java and do
not map directly to platform-specific peers. Thus, lightweight components are more efficient
and more flexible.
• Because lightweight components do not translate into native peers, the look and feel of each
component is determined by Swing, not by the underlying operating system. As a result, each
component will work in a consistent manner across all platforms.

2. Swing Supports a Pluggable Look and Feel


• Swing supports a pluggable look and feel (PLAF). Because each Swing component is
rendered by Java code rather than by native peers, the look and feel of a component is under
the control of Swing. This fact means that it is possible to separate the look and feel of a
component from the logic of the component, and this is what Swing does.
• Separating out the look and feel provides a significant advantage: it becomes possible to
change the way that a component is rendered without affecting any of its other aspects. In
other words, it is possible to “plug in” a new look and feel for any given component without
creating any side effects in the code that uses that component.
• Pluggable look-and-feels offer several important advantages. It is possible to define a look
and feel that is consistent across all platforms. Conversely, it is possible to create a look and
feel that acts like a specific platform. Finally, the look and feel can be changed dynamically at
run time. Dr. Vani V 4
No. AWT Swing
Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes and is
1.
applications in Java used to create various applications.

The components of Java AWT are heavy


2. The components of Java Swing are light weighted.
weighted.
Java AWT has comparatively less functionality Java Swing has more functionality as compared to
3.
as compared to Swing. AWT.
The execution time of AWT is more than
4. The execution time of Swing is less than AWT.
Swing.
The components of Java AWT are platform The components of Java Swing are platform
5.
dependent. independent.
6. MVC pattern is not supported by AWT. MVC pattern is supported by Swing.
AWT provides comparatively less powerful
7. Swing provides more powerful components.
components.

8 AWT components require [Link] package Swing components requires [Link] package

AWT is a thin layer of code on top of the Swing is much larger, swing also has very much
9
operating system. richer functionality.

Swing is also called as JFC(java Foundation classes). It


10 AWT stands for Abstract windows toolkit .
is part of oracle’s JFC.

Using AWT , you have to implement a lot of


11 Swing has them built in.
things yourself .
Dr. Vani V 5
The MVC Connection
Visual component is a composite of three distinct aspects:
1. The way that the component looks when rendered on the screen (View)
2. The way that the component reacts to the user (Controller)
3. The state information associated with the component (Model)

• No matter what architecture is used to implement a component, it must implicitly contain these
three parts. Over the years, one component architecture has proven itself to be exceptionally
effective: Model-View-Controller, or MVC for short.
• The MVC architecture is successful because each piece of the design corresponds to an aspect of
a component. In MVC terminology,
1. The model corresponds to the state information associated with the component. For example, in
the case of a check box, the model contains a field that indicates if the box is checked or
unchecked.
2. 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.
3. The controller determines how the component reacts to the user. For example, when the user
clicks a check box, the controller reacts by changing the model to reflect the user’s choice
(checked or unchecked). This then results in the view being updated.

• By separating a component into a model, a view, and a controller, the specific implementation of
each can be changed without affecting the other two. For instance, different view implementations
can render the same component in different ways without affecting the model or the controller.
• Swing uses a modified version of MVC that combines the view and the controller into a single
logical entity called the UI delegate. For this reason, Swing’s approach is called either the Model-
Delegate architecture or the Separable Model architecture.

Dr. Vani V 6
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: A component is an independent
visual control, such as a push button or slider. A container holds a group of components.
• 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. 1. Components
• Swing components are derived from the JComponent class.
• 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.
• All of Swing’s components are represented by classes defined within the package [Link]. The
following table shows the class names for Swing components (including those used as containers).

Advanced Java (BIS402) Dr. Vani V 7


2. Containers

Swing defines two types of containers.

1. Top-level containers: JFrame, JApplet, JWindow, and JDialog. These containers do not
inherit JComponent. They do, however, inherit the AWT classes Component and Container.
Unlike Swing’s other components, which are lightweight, the top-level containers are
heavyweight. This makes the top-level containers a special case in the Swing component
library. A top-level container must be at the top of a containment hierarchy. A top-level
container is not contained within any other container. Furthermore, every containment
hierarchy must begin with a top-level container. The one most commonly used for
applications is JFrame. The one used for applets is JApplet.
2. Lightweight containers. Lightweight containers do inherit JComponent. An example of a
lightweight container is JPanel, which is a general-purpose container. Lightweight containers
are often used to organize and manage groups of related components because a lightweight
container can be contained within another container. Thus, you can use lightweight
containers such as JPanel to create subgroups of related controls that are contained within
an outer container.

Advanced Java (BIS402) Dr. Vani V 8


The Top-Level Container Panes
• Each top-level container defines a set of panes. At the top of the hierarchy is an instance of JRootPane.
JRootPane is a lightweight container whose purpose is to manage the other panes. It also helps manage
the optional menu bar. The panes that comprise the root pane are called the glass pane, the content pane,
and the layered pane.
• The glassPane is the top-level pane. It sits above and completely covers all other panes. By default, it is a
transparent instance of JPanel. The glass pane enables you to manage mouse events that affect the entire
container (rather than an individual control) or to paint over any other component.
• The layered pane is an instance of JLayeredPane. The layered pane allows components to be given a
depth value. This value determines which component overlays another. (Thus, the layered pane lets you
specify a Z-order for a component, although this is not something that you will usually need to do.) The
layered pane holds the content pane and the (optional) menu bar.
• The pane with which your application will interact the most is the contentPane, because this is the pane to
which you will add visual components. In other words, when you add a component, such as a button, to a
top-level container, you will add it to the content pane. By default, the content pane is an opaque instance
of JPanel.

Advanced Java (BIS402) Dr. Vani V 9


The Swing Packages
• Swing is a very large subsystem and makes use of many packages.
• The main package is [Link]. 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.

Advanced Java (BIS402) Dr. Vani V 10


A Simple Swing Application
• Swing programs differ from both the console-based programs and the AWT-based programs.
For example, they use a different set of components and a different container hierarchy than
does the AWT.
• Swing programs also have special requirements that relate to threading. The best way to
understand the structure of a Swing program is to work through an example. There are two
types of Java programs in which Swing is typically used. The first is a desktop application.
The second is the applet.
• The following program shows one way to write a Swing application. In the process, it
demonstrates several key features of Swing. It uses two Swing components: JFrame and
JLabel. JFrame is the top-level container that is commonly used for Swing applications.
JLabel is the Swing component that creates a label, which is a component that displays
information. The label is Swing’s simplest component because it is passive. That is, a label
does not respond to user input. It just displays output. The program uses a JFrame container
to hold an instance of a JLabel. The label displays a short message.

Advanced Java (BIS402) Dr. Vani V 11


Advanced Java (BIS402) Dr. Vani V 12
• The program declares the SwingDemo class and a constructor for that class. The constructor is where
most of the action of the program occurs. It begins by creating a JFrame, using this line of code:
JFrame jfrm = new JFrame("A Simple Swing Application");
This creates a container called jfrm that defines a rectangular window complete with a title bar; close, minimize,
maximize, and restore buttons; and a system menu. Thus, it creates a standard, top-level window. The title of
the window is passed to the constructor.

• Next, the window is sized using this statement:


[Link](275, 100);
The setSize( ) method (which is inherited by JFrame from the AWT class Component) sets the dimensions of
the window, which are specified in pixels. Its general form is shown here:
void setSize(int width, int height)

• By default, when a top-level window is closed (such as when the user clicks the close box), the window is
removed from the screen, but the application is not terminated. While this default behavior is useful in some
situations, it is not what is needed for most applications. Instead, you will usually want the entire application
to terminate when its top-level window is closed. There are a couple of ways to achieve this. The easiest
way is to call setDefaultCloseOperation( ), as the program does:
[Link](JFrame.EXIT_ON_CLOSE);
• After this call executes, closing the window causes the entire application to terminate. The general form of
setDefaultCloseOperation( ) is shown here:
void setDefaultCloseOperation(int what)
• The value passed in what determines what happens when the window is closed. There are several other
options in addition to JFrame.EXIT_ON_CLOSE. They are shown here:
DISPOSE_ON_CLOSE
HIDE_ON_CLOSE
DO_NOTHING_ON_CLOSE
These constants are declared in WindowConstants, which is an interface declared in [Link] that is
implemented by Jframe.

Advanced Java (BIS402) Dr. Vani V 13


• The next line of code creates a Swing JLabel component:
JLabel jlab = new JLabel(" Swing means powerful GUIs.");
JLabel is the simplest and easiest-to-use component because it does not accept user input. It simply displays
information, which can consist of text, an icon, or a combination of the two. The label created by the program
contains only text, which is passed to its constructor.

• The next line of code adds the label to the content pane of the frame:
[Link](jlab);
All top-level containers have a content pane in which components are stored. Thus, to add a component to a
frame, you must add it to the frame’s content pane. This is accomplished by calling add( ) on the Jframe
reference (jfrm in this case). The general form of add( ) is shown here:
Component add(Component comp)
The add( ) method is inherited by JFrame from the AWT class Container.
By default, the content pane associated with a JFrame uses border layout.

The last statement in the SwingDemo constructor causes the window to become visible:
[Link](true);
The setVisible( ) method is inherited from the AWT Component class. If its argument is true, the window will
be displayed. Otherwise, it will be hidden. By default, a JFrame is invisible, so setVisible(true) must be called
to show it.

Inside main( ), a SwingDemo object is created, which causes the window and the label to be displayed. This
sequence causes a SwingDemo object to be created on the event dispatching thread rather than on the main
thread of the application. Here’s why. In general, Swing programs are event-driven. For example, when a user
interacts with a component, an event is generated. An event is passed to the application by calling an event
handler defined by the application.

Advanced Java (BIS402) Dr. Vani V 14


• However, the handler is executed on the event dispatching thread provided by Swing and not on the main
thread of the application. Thus, although event handlers are defined by your program, they are called on a
thread that was not created by your program.
• To avoid problems (including the potential for deadlock), all Swing GUI components must be created and
updated from the event dispatching thread, not the main thread of the application. However, main( ) is
executed on the main thread. Thus, main( ) cannot directly instantiate a SwingDemo object. Instead, it must
create a Runnable object that executes on the event dispatching thread and have this object create the GUI.
To enable the GUI code to be created on the event dispatching thread, you must use one of two methods
that are defined by the SwingUtilities class. These methods are

static void invokeLater(Runnable obj)


static void invokeAndWait(Runnable obj) throws InterruptedException, InvocationTargetException

• Here, obj is a Runnable object that will have its run( ) method called by the event dispatching thread. The
difference between the two methods is that invokeLater( ) returns immediately, but invokeAndWait( ) waits
until [Link]( ) returns. You can use one of these methods to call a method that constructs the GUI for your
Swing application, or whenever you need to modify the state of the GUI from code not executed by the event
dispatching thread. You will normally want to use invokeLater( ), as the preceding program does. However,
when constructing the initial GUI for an applet, you will need to use invokeAndWait( ).

Advanced Java (BIS402) Dr. Vani V 15


Event Handling
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 [Link]. Events specific to Swing are stored in [Link].

Advanced Java (BIS402) Dr. Vani V 16


The [Link] package is needed because it contains the FlowLayout class, which supports the standard flow
layout manager used to lay out components in a frame. The [Link] 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:
[Link](new FlowLayout());
JButton jbtnAlpha = new JButton("Alpha");
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)
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. Tthe ActionListener interface defines only one method:
actionPerformed( ).
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.
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:
[Link]( (ae) -> [Link]("Alpha was pressed."));

The buttons are added to the content pane of jfrm:


[Link](jbtnAlpha);
[Link](jbtnBeta);
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.
Advanced Java (BIS402) Dr. Vani V 17
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 : init( ), start( ), stop( ), and destroy( ). We need to
override only those methods that are needed by our applet.
• Painting is accomplished differently in Swing than it is in the AWT, and a Swing applet will not normally
override the paint( ) method.
• All interaction with components in a Swing applet must take place on the event dispatching thread.

• There are two important things to notice about this applet. First, MySwingApplet extends JApplet. As
explained, all Swing-based applets extend JApplet rather than Applet.
• Second, the init( ) method initializes the Swing components on the event dispatching thread by setting
up a call to makeGUI( ). Notice that this is accomplished through the use of invokeAndWait( ) rather
than invokeLater( ). Applets must use invokeAndWait( ) because the init( ) method must not return until
the entire initialization process has been completed. In essence, the start( ) method cannot be called
until after initialization, which means that the GUI must be fully constructed.
• Inside makeGUI( ), the two buttons and label are created, and the action listeners are added to the
buttons. Finally, the components are added to the content pane. Although this example is quite simple,
this same general approach must be used when building any Swing GUI that will be used by an applet.
Advanced Java (BIS402) Dr. Vani V 18
Advanced Java (BIS402) Dr. Vani V 19
Painting in Swing
• Swing’s approach to painting is built on the original AWT-based mechanism, but Swing’s implementation offers more
finally grained control. The AWT class Component defines a method called paint( ) that is used to draw output directly
to the surface of a component.
• Because JComponent inherits Component, all Swing’s lightweight components inherit the paint( ) method. However,
we will not override it to paint directly to the surface of a component. The reason is that Swing uses a bit more
sophisticated approach to painting that involves three distinct methods: paintComponent( ), paintBorder( ), and
paintChildren( ).
• These methods paint the indicated portion of a component and divide the painting process into its three distinct,
logical actions. In a lightweight component, the original AWT method paint( ) simply executes calls to these methods,
in the order just shown.
• To paint to the surface of a Swing component, create a subclass of the component and then override its
paintComponent( ) method. This is the method that paints the interior of the component. You will not normally
override the other two painting methods. When overriding paintComponent( ), the first thing you must do is call
[Link]( ), so that the superclass portion of the painting process takes place.
• After that, write the output that you want to display. 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. Calling it causes the system to call paint( ) as soon as it is
possible to do so. Because painting is a time-consuming operation, this mechanism allows the run-time system to
defer painting momentarily until some higher-priority task has completed, for example. Of course, in Swing the call to
paint( ) results in a call to paintComponent( ). Therefore, to output to the surface of a component, your program will
store the output until paintComponent( ) is called. Inside the overridden paintComponent( ), you will draw the stored
output.

Advanced Java (BIS402) Dr. Vani V 20


Advanced Java (BIS402) Dr. Vani V 21
The PaintPanel class extends JPanel. JPanel is one of Swing’s lightweight containers, which means that it is a
component that can be added to the content pane of a JFrame.
To handle painting, PaintPanel overrides the paintComponent( ) method. This enables PaintPanel to write
directly to the surface of the component when painting takes place. The size of the panel is not specified because
the program uses the default border layout and the panel is added to the center.

Notice that the constructor also specifies a 5-pixel wide, red border. This is accomplished by setting the border by
using the setBorder( ) method, shown here:
void setBorder(Border border)

Border is the Swing interface that encapsulates a border. You can obtain a border by calling one of the factory
methods defined by the BorderFactory class. The one used in the program is createLineBorder( ), which creates
a simple line border. It is shown here:
static Border createLineBorder(Color clr, int width)

Here, clr specifies the color of the border and width specifies its width in pixels. Inside the override of
paintComponent( ), notice that it first calls [Link]( ). As explained, this is necessary to ensure
that the component is properly drawn. Next, the width and height of the panel are obtained along with the insets.
These values are used to ensure the lines lie within the drawing area of the panel. The drawing area is the overall
width and height of a component less the border width. The computations are designed to work with differently
sized PaintPanels and borders

The PaintDemo class creates a PaintPanel and then adds the panel to the content pane. When the application is
first displayed, the overridden paintComponent( ) method is called, and the lines are drawn. Each time you resize
or hide and restore the window, a new set of lines are drawn. In all cases, the lines fall within the paintable area.

Advanced Java (BIS402) Dr. Vani V 22


Swing Components

The Swing components provide rich functionality and allow a high level of customization. These
components are all lightweight, which means that they are all derived from JComponent.
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
[Link].
The Swing components are demonstrated in applets because the code for an applet is more
compact than it is for a desktop application. However, the same techniques apply to both
applets and applications.

Advanced Java (BIS402) Dr. Vani V 23


JLabel and ImageIcon
JLabel is Swing’s easiest-to-use component and it creates a label. 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
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 implement 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) Dr. Vani V
Advanced Java (BIS402) Dr. Vani V 25
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.
• 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 [Link].)
• We can simply obtain the string currently in the text field when it is needed. To obtain the text
currently in the text field, call getText( ).

Advanced Java (BIS402) Dr. Vani V 26


Advanced Java (BIS402) Dr. Vani V 27
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.

Advanced Java (BIS402) Dr. Vani V 28


JButton
• 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.
• Three of its constructors are shown here:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
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, we can obtain the
action command string associated with the button. By default, this is the string displayed
inside the button.
• setActionCommand() is used to set the action command on the button. getActionCommand()
obtain the action command on the event object.
• 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.

Advanced Java (BIS402) Dr. Vani V 29


Advanced Java (BIS402) Dr. Vani V 30
JToggleButton
• 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. Thus, JToggleButton defines the basic functionality of all two-
state components.
• JToggleButton(String str) is a constructor used to create a toggle button that contains the
text passed in str. By default, the button is in the off position. Other constructors enable us to
create toggle buttons that contain images, or images and text.
• 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.
• 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.
boolean isSelected( ) It returns true if the button is selected and false otherwise.

Dr. Vani V 31
Advanced Java (BIS402) Dr. Vani V 32
Check Boxes
• The JCheckBox class provides the functionality of a check box. Its immediate superclass is
JToggleButton, which provides support for two-state buttons,.
• 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. We 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 getText( ) method gets the text for that check box and uses it to set the text inside the
label.

Dr. Vani V 33
Advanced Java (BIS402) Dr. Vani V 34
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. Example
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)
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 we 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.
1. 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.
2. Second, you can call getSource( ) on the ActionEvent object and check that reference against the
buttons.
3. Third, you can check each radio button to find out which one is currently selected by calling
isSelected( ) on each button.
4. Finally, each button could use its own action event handler implemented as either an anonymous inner
class or a lambda expression. Dr. Vani V 35
Advanced Java (BIS402) Dr. Vani V 36

You might also like