0% found this document useful (0 votes)
31 views21 pages

OODJ Module-5

K

Uploaded by

royaljaanu6
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)
31 views21 pages

OODJ Module-5

K

Uploaded by

royaljaanu6
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/ 21

Module-5 Event and GUI Programming

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

3. Two Key Swing Features


● Swing was created to address the limitations present in the AWT.
● It does this through two key features:
○ Lightweight components
○ A pluggable look and feel
● Together they provide an elegant, easy-to-use solution to the problems of the AWT.

3.1Swing Components Are Lightweight


● With very few exceptions, Swing components are lightweight.
● 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.
● Thus each component will work in a consistent manner across all platforms.

3.2Swing 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.
● 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.
● Moreover, it becomes possible to define entire sets of look-and-feels that represent different
GUI styles.
● Once this is done, all components are automatically rendered using that style.

Advantages of a Pluggable Look and Feel


● 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.
● For example, if we know that an application will be running only in a Windows
environment, it is possible to specify the Windows look and feel.
● It is also possible to design a custom look and feel.
● Finally, the look and feel can be changed dynamically at run time.
4. The MVC Connection - MVC (Model-View-Controller) Architecture
● In general, a visual component is a composite of three distinct aspects:
○ The way that the component looks when rendered on the screen
○ The way that the component reacts to the user
○ The state information associated with the component
● 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 (MVC).

4.1The MVC Connection - Swing


● The MVC architecture is successful because each piece of the design corresponds to
an aspect of a component.
● 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.
● 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.

6. The Swing Packages


● Swing is a very large subsystem and makes use of many packages.
● 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.

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 window is sized using the following statement


jfrm.setSize(400,400);

● Alternatively title of the window may be set as


jfrm.setTitle(“xxxx”);
● 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.
● We may require the entire application to terminate when its top-level window is closed.
● One of the method to do this to call setDefaultCloseOperation( )

● 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

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

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

● Layout refers to the arrangement of components within the container.


● The layout manager automatically positions all the components within the container.
● Even if you do not use the layout manager, the components are still positioned by the default
layout manager.
● We can use any one of the layout available for the frame. Accordingly we have to import the
package also. E.g.

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

Sample Program-4 (displaying icon on label)

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

Sample Program-6 demonstrating class implementing ActionListener Interface


B. Anonymous class
● We can create an inner class without specifying a name this is known as an anonymous
inner class.
● Anonymous inner classes can make our code easier to read because the class is defined
where it is referenced.
● However, we need to weigh the convenience against possible performance implications of
increasing the number of classes.

Sample Program-7 demonstrating use of anonymous class


Sample Program-8 (text field with some action)

12.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.
● The text associated with a button can be read and written via the following methods:

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

Sample Program-9 (button without any action)

Sample Program-10 (button with image without any action)


Sample Program-11 (button with action)

Sample Program-12 (button with image and action)


Extra Programs for learning
Program – use of Checkbox
Program – use of Radiobutton
Program – Simple Calculator
Program – Login page for database access
Program for Userhome required in previous program

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

***************End of Module-5 ***************

You might also like