Understanding Java Swing Architecture
Understanding Java Swing Architecture
Module 3 SWINGS
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. AWT 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.
Drawbacks of AWT :
1. Because of variations between operating systems, a component might look, or even act, differently on
different platforms. This potential variability threatened the overarching philosophy of Java: write once,
run anywhere.
2. The look and feel of each component was fixed (because it is defined by the platform) and could not be
(easily) changed.
3. The use of heavyweight components caused some frustrating restrictions. For example, a heavyweight
component was always opaque.
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.
● With Java 1.2, Swing (and the rest of the JFC) was fully integrated into Java.
Swing does not replace AWT. Instead, Swing is built on the foundation of the AWT. 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.
• The way that the component looks when rendered on the screen -- VIEW
In MVC terminology, 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.
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. 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.
The controller acts as an interface between view and model. It intercepts all the requests i.e. receives input and
commands to Model / View to change accordingly.
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.
Swing’s pluggable look and feel is made possible by its Model-Delegate architecture. Because the view (look) and
controller (feel) are separate from the model, the look and feel can be changed without affecting how the
component is used within a program. Conversely, it is possible to customize the model without affecting the way
that the component appears on the screen or responds to user input.
AWT Swing
AWT components are platform- dependent Swing components are platform-independent.
AWT components are heavyweight. Swing components are lightweight.
AWT provides less components than Swing. Swing provides more powerful components such as
tables, lists, scrollpanes, colorchooser and etc.
AWT doesn't follows MVC(Model View Controller) where Swing follows MVC.
model represents data, view represents presentation
and controller acts as an interface between model and
view.
Component is an independent visual control. A container holds a group of components. Thus, a container is a
special type of component that is designed to hold other components. 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.
Since 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
● Swing components are derived from the JComponent class. (Exceptions the four top-level containers
JFrame, JApplet, JWindow, and JDialog).
● JComponent provides the functionality that is common to all components.
● JComponent supports the pluggable look and feel. JComponent class 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].
● All component classes begin with the letter J.
The following table shows the class names for Swing components (including those used as containers).
Containers
1) The first are top-level containers: JFrame, JApplet, JWindow, and JDialog. The top-level containers are
heavyweight because they inherit the AWT classes Component and Container. A top-level container must
be at the top of a containment hierarchy. A top-level container is not contained within any other
container. The most commonly used container for Java standalone applications is JFrame.
2) The second type of containers supported by Swing are lightweight containers. Lightweight containers
inherit JComponent. A general-purpose lightweight container is JPanel. Lightweight containers are often
used to organize and manage groups of related components because a lightweight container can be
contained within another container.
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 content pane, 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.
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.
JFrame:
Frame represents a window with a title bar and borders. Frame becomes the basis for creating the GUIs for an
application because all the components go into the frame. To create a frame, we have to create an object to
JFrame class in swing as
To close the frame, use setDefaultCloseOperation() method of JFrame class . Closing the window causes the
entire application to terminate.
JFrame.EXIT_ON_CLOSE This closes the application upon clicking the close button
JFrame.DISPOSE_ON_CLOSE close button This closes the application upon clicking the close button
JFrame.DO_NOTHING_ON_CLOSE This will not perform any operation upon clicking close button
JFrame.HIDE_ON_CLOSE This hides the frame upon clicking close button
To create simple swing example, you need a frame. In swing, we use JFrame class to create a frame. There are
two ways to create a frame in swing.
…….. }
…….. }
import [Link].*;
(OR) In Constructor()
import [Link].*;
Components of Swing:
JComponent:
The class JComponent is the base class for all Swing components except top-level containers.
Constructor: JComponent();
The following are the JComponent class's methods to manipulate the appearance of the component.
● JLabel(Icon icon)
● JLabel(String str)
● JLabel(String str, Icon icon, int align)
Here, str and icon are the text and image icon used to display on 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 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.
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.
JTextField
● JTextField is the simplest and most widely used Swing 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.
● 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 several types ofevents in response to user interaction. Commonly handled events are:
Prof Vasanthalakshmi M, Dept of ISE, SCE 8
Module – 3 Swings
To obtain the string or text currently in the text field call getText( ).
● Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and JRadioButton.
● All are subclasses of the AbstractButton class, which extends JComponent.
● 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.
● The text associated with a button can be read and written via the following methods:
The model used by all buttons is defined by the ButtonModel interface. A button generates an action event
when it is pressed.
JButton
● JButton(Icon icon)
● JButton(String str)
● JButton(String str, Icon icon)
Here, str and icon are the string and image icon used for the button.
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.
We can set and obtain the action command by calling setActionCommand( ) on the button and method
getActionCommand( ) on the event object. It is declared like this:
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.
JToggleButton
1. JToggleButton(): Creates an initially unselected toggle button without setting the text or image.
2. JToggleButton(Icon icon): Creates an initially unselected toggle button with the specified image but no text.
3. JToggleButton(Icon icon, boolean selected): Creates a toggle button with the specified image and selection
state, but no text.
4. JToggleButton(String text): Creates an unselected toggle button with the specified text.
5. JToggleButton(String text, boolean selected): Creates a toggle button with the specified text and selection
state.
6. JToggleButton(String text, Icon icon): Creates a toggle button that has the specified text and image, and
that is initially unselected.
7. JToggleButton(String text, Icon icon, boolean selected): Creates a toggle button with the specified text,
image, and selection state.
Like JButton, JToggleButton generates an action event each time it is pressed and also generates an item event.
Item 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. 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:
To determine a toggle button’s state , isSelected( ) method is called on the button that generated the event.
● boolean isSelected( ) It returns true if the button is selected and false otherwise
● public void setText(String text): This method sets the text which appears on the button.
● public void setSelected(boolean b): This method sets the state of the button. If b is true, the button will
appear selected and if b is false, the button will appear de-selected.
● public void setEnabled(boolean b): This method is used to disable the button. If b is false, the button will
be grayed out and will no more be clickable.
● public void addActionListener(ActionListener l): This method attached an action listener to this button
so that any action performed on this button can be catched at the backend.
● public void addItemListener(ItemListener l): This method attaches an item listener to this button so that
the selection and deselection of this button can be handled at the backend.
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. Some of its constructors are shown here:
● JCheckBox(Icon i)
● JCheckBox(Icon i, boolean state)
● JCheckBox(String s)
● JCheckBox(String s, boolean state)
● JCheckBox(String s, Icon i)
● JCheckBox(String s, Icon i, boolean state)
The state of the check box can be changed via the following method: void setSelected(boolean state)
When the user selects or deselects a check box, an ItemEvent is generated. This is handled by itemStateChanged( )
method defined by ItemListener class.
The getItem( ) method gets the JCheckBox object that generated the event.
The easiest way to determine the selected state of a check box is to call isSelected( ) on the JCheckBox instance.
Radio Buttons:
Radio buttons are supported by the JRadioButton class, which is a concrete implementation of AbstractButton. Its
immediate superclass is JToggleButton, which provides support for two-state buttons. Some of its constructors are
shown here:
● JRadioButton(Icon i)
● JRadioButton(Icon i, boolean state)
● JRadioButton(String s)
● JRadioButton(String s, boolean state)
● JRadioButton(String s, Icon i)
● JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is true, the button is initially selected. Otherwise, it
is not.
Radio buttons must be configured into a group. Only one of the buttons in that group can be selected at any time.
For example, if a user presses a radio button that is in a group, any previously selected button in that group is
automatically deselected. The ButtonGroup class is instantiated to create a button group. Its default constructor is
invoked for this purpose. Elements are then added to the button group via the following method:
void add(AbstractButton ab) Here, ab is a reference to the button to be added to the group.
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.
Inside the method actionPerformed( ) defined by ActionListener, we 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. 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.
1. The program uses a JFrame container to hold an instance of a JLabel. The label displays a short text message.
import [Link].*;
class SwingDemo { SwingDemo() {
2. /*creates a JTextField and adds it to the content pane. When the user presses enter key, an action event is
generated. This is handled by displaying the text in a label.*/
package tf;
import [Link].*;
import [Link].*;
import [Link].*;
public class Tf {
public Tf() {
// Add a label.
JLabel jlab = new JLabel();
[Link](jlab);
import [Link].*;
import [Link].*;
import [Link].*;
public Button() {
[Link]();
[Link](true);
}
4. /*Demonstrate ToggleButton. Create a togglebutton with text “on/off” on it. When it is pressed , the
corresponding event handler must display “ button is ON” on label and when the button is released , text
displayed is “Button is OFF” */
package tog;
import [Link].*;
import [Link].*;
import [Link].*;
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent ie)
{
if([Link]())
[Link]("Button is on.");
else
[Link]("Button is off.");
} });
[Link](jtbn);
[Link](jlab);
[Link](true);
}
/* 5 . It displays four check boxes and a label. When the user clicks a check box, an ItemEvent is generated. The text
for that check box is used to set the text inside the label. */
package chbox;
import [Link].*;
import [Link].*;
import [Link].*;
cb = new JCheckBox("C++");
[Link](this);
[Link](cb);
cb = new JCheckBox("Java");
[Link](this);
[Link](cb);
cb = new JCheckBox("Perl");
[Link](this);
[Link](cb);
/*6. Demonstrate RadioButton. Three radio buttons are created. The buttons are then added to a button group.
Within the handler, get the text that is associated with the radio button and uses it to set the text within a label. */
import [Link].*;
import [Link].*;
import [Link].*;
8. Along with these programs , learn one Lab pgm on Alpha, Beta buttons