OODJ Module-5
OODJ Module-5
● Introducing Swing
● The Origins of Swing
● Swing Is Built on the AWT
● Two Key Swing Features
● The MVC Connection
● Components and Containers
● The Swing Packages
● A Simple Swing Application
● Event Handling
● JLabel; JTextField; JButton
1. Introducing Swing
● Swing was a response to deficiencies present in Java‟s original GUI subsystem i.e.
Abstract Window Toolkit (AWT)
● Swing is a set of classes that provides more powerful and flexible GUI components than
AWT.
● Swing provides the look and feel of the Java GUI.
● 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.
● 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 rectangular and opaque.
● After Java‟s original release, it became apparent that the limitations and restrictions
present in the AWT were sufficiently serious that a better approach was needed.
● 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.
2. Swing Is Built on the 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.
● 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.
● It is possible to customize the model without affecting the way that the component appears
on the screen or responds to user input.
● To support the Model-Delegate architecture, most Swing components contain two objects.
● The first represents the model.
● The second represents the UI delegate.
● For example, the model for a button is defined by the ButtonModel interface.
● UI delegates are classes that inherit ComponentUI.
● For example, the UI delegate for a button is ButtonUI.
5. 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:
○ A container holds a group of components.
○ A component is an independent visual control, such as a push button or slider.
● 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.
● Because containers are components, a container can also hold other containers.
● This enables Swing to define a containment hierarchy, at the top of which must be a top-
level container.
5.1Components
● In general, 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 javax.swing.
● All component classes begin with the letter J.
5.2Containers
● Swing defines two types of containers.
● The first are top-level containers: JFrame, JApplet, JWindow, and JDialog.
● These containers do not inherit JComponent.
● They inherit the AWT classes Component and Container.
● 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.
● Every containment hierarchy must begin with a top-level container.
● The most commonly used for applications is JFrame.
● The one used for applets is JApplet.
● The second type of containers supported by Swing is 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, we can use lightweight containers such as JPanel to create subgroups of
related controls that are contained within an outer container.
7. Swing - JFrame
● JFrame and other components can be created using any of the following methods:
● JFrame and other component objects are created inside the main() method directly.
● We can write all the codes of creating JFrame, JButton and method calls inside the
java constructor, and then create the
● We can also inherit the JFrame class, so there is no need to create the instance of
JFrame class explicitly.
● Following statement 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.
JFrame jfrm = new JFrame("GUI Application");
● 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.
● DISPOSE_ON_CLOSE
● HIDE_ON_CLOSE
● DO_NOTHING_ON_CLOSE
● 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.
● All top-level containers have a content pane in which components are stored.
● Thus, to add a component to a frame, we must add it to the frame‟s content pane.
● This is accomplished by calling add( ) on the JFrame reference.
● The add( ) method is inherited by JFrame from the AWT class Container.
8. Swing - JPanel
● A panel is an instance of JPanel.
● A frame can have more than one panels and each panel can have several components.
● Panels are useful for grouping components and placing them to appropriate locations in a
frame.
Sample Program-1
● In above program, inside main( ), a Swing1 object is created, which causes the window
and the label to be displayed.
● The code causes a Swing1 object to be created on the event dispatching thread rather than
on the main thread of the application.
● 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.
● 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 the program, they are called on a thread
that was not created by the 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( ) does not directly instantiate an object.
● Instead, it creates a Runnable object that executes on the event dispatching thread and makes
this object creating the GUI.
● To enable the GUI code to be created on the event dispatching thread, we must use one of
two methods that are defined by the SwingUtilities class.
● These methods are invokeLater( ) and invokeAndWait( ).
● The difference between the two methods is that invokeLater( ) returns immediately, but
invokeAndWait( ) waits until run( ) returns.
● We can use one of these methods to call a method that constructs the GUI for the Swing
application, or whenever we need to modify the state of the GUI from code not executed by
the event dispatching thread.
● We will normally want to use invokeLater( ).
● However, when constructing the initial GUI for an applet, we will need to use
invokeAndWait( ).
9. Swing - JLabel
● A display area for a short text string or an image, or both.
● A label does not react to input events.
● As a result, it cannot get the keyboard focus.
● A label can, however, display a keyboard alternative as a convenience for a nearby
component that has a keyboard alternative but can't display it.
● We can specify the alignment of the label's contents by setting the vertical and horizontal
alignment.
● By default, labels are vertically centered in their display area.
● Text-only labels are leading edge aligned, by default; image-only labels are horizontally
centered, by default.
● JLabel defines several constructors.
● JLabel()
● Creates a JLabel instance with no image and with an empty string for the title.
● JLabel(Icon image)
● Creates a JLabel instance with the specified image.
● JLabel(Icon image, int horizontalAlignment)
● Creates a JLabel instance with the specified image and horizontal alignment.
● JLabel(String text)
● Creates a JLabel instance with the specified text.
● JLabel(String text, int horizontalAlignment)
● Creates a JLabel instance with the specified text and horizontal alignment.
● JLabel(String text, Icon icon, int horizontalAlignment)
● Creates a JLabel instance with the specified text, image, and horizontal
alignment.
● Here, text 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.
● 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.
ImageIcon(String filename)
● The icon and text associated with the label can be obtained by the following methods:
● The icon and text associated with a label can be set by these methods:
● Using setText( ), it is possible to change the text inside a label during program execution.
Sample Program-2
Sample Program-3
10.Swing - JTextField
● JTextField is the simplest Swing text component.
● It is most widely used text component.
● JTextField allows us to edit one line of text.
● It is derived from JTextComponent, which provides the basic functionality common to
Swing text components.
● JTextField()
● Constructs a new TextField.
● JTextField(int columns)
● Constructs a new empty TextField with the specified number of columns.
● JTextField(String text)
● Constructs a new TextField initialized with the specified text.
● JTextField(String text, int columns)
● Constructs a new TextField initialized with the specified text and columns.
Sample Program-5
11.Event Handling
● JLabel does not take input from the user, it does not generate events, so no event handling
was needed.
● However, the other Swing components such as textfields, button etc. 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.
● 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.
● Events specific to Swing are stored in javax.swing.event.
11.1 Event Handling Mechanism/Code
● We can use the event handling code in one of the following ways:
A. Within class
● This is a common approach to implement the ActionListener.
● If we implement the ActionListener interface, we need to follow 3 steps:
● Implement the ActionListener interface in the class
● Register the component with the Listener
● Override the actionPerformed() method
● AbstractButton contains many methods that allow us to control the behavior of buttons.
● We can define different icons that are displayed for the button when it is disabled, pressed,
or selected.
● The following methods set these icons:
○ void setDisabledIcon(Icon di)
○ void setPressedIcon(Icon pi)
○ void setSelectedIcon(Icon si)
○ void setRolloverIcon(Icon ri)
13.Swing - 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.
● The text associated with a button can be read and written via the following methods
● JButton()
● Creates a button with no set text or icon.
● JButton(Icon icon)
● Creates a button with an icon.
● JButton(String text)
● Creates a button with text.
● JButton(String text, Icon icon)
● Creates a button with initial text and an icon.
Questions
1. What is the difference between Swing and AWT in Java?
2. What is the difference between Container and Component?
3. What are the key features of Swing? Describe briefly.
4. How can you handle an event in a Swing program having a button? Write code snippet.
5. What is Model-View-Controller Architecture? How does Swing make use of MVC
architecture?
6. Write a Swing program which includes one textfield, one label and one button. When the
button is clicked, textfield should display „Welcome‟.
7. Explain event handling mechanism used by Swing with Java code snippet.
8. Write Swing code snippet to set any four properties of JFrame.
9. Describe two constructors and two methods which can be used with JLabel. Write code
snippets to support your answer.
10. Describe two constructors and two methods which can be used with JButton. Write code
snippets to support your answer.
11. Describe two constructors and two methods which can be used with JTextField. Write code
snippets to support your answer