GUI
GUI
GUI Programming
A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an
application.
A GUI (pronounced “GOO-ee”) gives an application a distinctive “look and feel.” GUIs are built from
GUI components. These are sometimes called controls or widgets—short for window gadgets. A
GUI component is an object with which the user interacts via the mouse, the keyboard or another
form of input, such as voice recognition.
Common Terms
Some familiar terms associated with GUI programs include :
a) Window - A GUI program runs within a window. One window at a time has focus and
receives input from the keyboard and mouse.
b) Menus - Commands the program accepts may be organized on menus, usually along the
top of a window.
c) Components-These are sometimes called controls or widgets—short for window gadgets. A
GUI component is an object with which the user interacts via the mouse, the keyboard or
another form of input, such as voice recognition.
d) container is a special component that holds and organizes other components
dialog boxes, applets, frames, panels, etc.
e) An event is an object that represents some activity to which we may want to respond . For
example, we may want our program to perform some action when the following occurs:
the mouse is moved
a mouse button is clicked
the mouse is dragged
f) A listener is an object that awaits an event to occur.
g) Layout manager:An object contained inside frames and other graphical containers that
decides the position and size of the components inside the container.
java.awt package
// instantiate components
Swing API
Swing API is a set of extensible GUI Components to ease the developer's life to create JAVA
based Front End/GUI Applications. It is built on top of AWT API and acts as a replacement of
AWT API, since it has almost every control corresponding to AWT controls. The diagram below
shows the inheritance hierarchy of classes from which lightweight Swing components inherit their
common attributes and behaviors.
Class Component (package java.awt) is a superclass that declares the common features of GUI
components in packages java.awt and javax.swing. A Component is the abstract base class for the
GUI Programming
Any object that is a Container (package java.awt) can be used to organize Components by
attaching the Components to the Container. A Container is a component that can contain other
SWING components. Containers can be placed in other Containers to organize a GUI.
Class JComponent (package javax.swing) is a subclass of Container.
JComponent is the superclass of all lightweight Swing components and declares their common
attributes and behaviors. Because JComponent is a subclass of Container, all lightweight
Swing components are also Container.
Swing Features
Light Weight − Swing components are independent of native Operating System's API as
Swing API controls are rendered mostly using pure JAVA code instead of underlying
operating system calls.
Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane,
slider, colorpicker, and table controls.
Highly Customizable − Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
Pluggable look-and-feel – swing-based GUI Application look and feel can be changed at
run-time, based on available values.
Tool tips- Brief descriptions of a GUI component’s purpose (called tool tips) that are
displayed when the mouse cursor is positioned over the component for a short time.
AWT swing
Platform dependent –dependent on Platform-independent-purely scripted
the platform in java
Heavyweight Largely lightweight-most components
do not need any native OS objects for
implementing their functionality.
Do not support pluggable look and Support pluggable look and feel
feel
Components are less in number Richer controls both in numbers and feature
and features. support
GUI Programming
Like the with the awt package, programming a user interface with swing involves the following
aspects:
7 JComboBox
A drop-down list of items from which the user can make a selection
8 JTextField
GUI Programming
A text field is a basic text control that enables the user to type a small amount of text. When the
user indicates that text entry is complete (usually by pressing Enter), the text field fires an action
event. If you need to obtain more than one line of input from the user, use a text area. A
JTextField object is a text component that allows for the editing of a single line of text.
JPasswordField
9
A JPasswordField object is a text component specialized for password entry.
JTextArea
A JTextArea object is a text component that allows editing of a multiple lines of text. A text
10
area is a multi-line text field
ImageIcon
11 A ImageIcon control is an implementation of the Icon interface that paints Icons from
Images
JScrollbar
12 A Scrollbar control represents a scroll bar component in order to enable the user to select
from range of values.
JOptionPane
13 JOptionPane provides set of standard dialog boxes that prompt users for a value or informs
them of something.
JFileChooser
14
A JFileChooser control represents a dialog window from which the user can select a file.
JProgressBar
15 As the task progresses towards completion, the progress bar displays the task's percentage of
completion.
JSlider
16
A JSlider lets the user graphically select a value by sliding a knob within a bounded interval.
JSpinner
17 A JSpinner is a single line input field that lets the user select a number or an object value
from an ordered sequence.
JOptionPane class
Most applications on a daily basis use windows or dialog boxes (also called dialogs) to interact
with the user.
Dialog boxes are windows in which programs display important messages to the user or obtain
information from the user.
Java’s JOptionPane class (package javax.swing) provides prebuilt dialog boxes for both input
and output.
Dialog Types
The JOptionPane provides the following dialog boxes:
1. Message Dialog
To create the message dialog, you invoke the JOptionPane’s showMessageDialog method.
The method is overloaded with the following two versions:
a) showMessageDialog(<parent>, <message>)
Displays a message on a dialog with an OK button.
Eg JOptionPane.showMessageDialog(null, “Hello World”);
b) showMessageDialog(<parent>, <message>,<title>,<messagetype>)
The first argument helps the Java application determine where to position the dialog box. If
the first argument is null, the dialog box is displayed at the center of your screen.
The second argument is the message to display.
The third argument—"Message Dialog "—is the String that should appear in the title bar at the top
of the dialog.
The fourth argument—JOptionPane.PLAIN_MESSAGE—is the type of message dialog to display.
A PLAIN_MESSAGE dialog does not display an icon to the left of the message.
Note : message type can be any of the following integer valued constants :
.INFORMATION_MESSAGE, PLAIN_MESSAGE, WARNING_MESSAGE,
ERROR_MESSAGE, QUESTION_MESSAGE
2. Input Dialog
3. Confirm Dialog
import javax.swing.JOptionPane;
public class DialogBoxes
{
public static void main(String args[])
{
//message dialog
JOptionPane.showMessageDialog(null, "Welcome to GUI programming",
"GUI",JOptionPane.INFORMATION_MESSAGE);
// input Dialog
String name=JOptionPane.showInputDialog(null,"Enter your name");
//message dialog
JOptionPane.showMessageDialog(null, name, "Name
Dialog",JOptionPane.INFORMATION_MESSAGE);
// confirm Dialog
int choice = JOptionPane.showConfirmDialog(null, "Restart your computer?");
if (choice == JOptionPane.YES_OPTION)
JOptionPane.showMessageDialog(null, "Restarting!");
else if(choice == JOptionPane.NO_OPTION)
JOptionPane.showMessageDialog(null, "Restart later !");
else
JOptionPane.showMessageDialog(null, "Cancel Restart!");
}
}
Input Dialogs:
The JOptionPane static method showInputDialog displays an input dialog, using the method’s
String argument ("Enter first integer") as a prompt. From the example the following statement calls the
showInputDialog method.
String firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
Message Dialogs:
The JOptionPane static method showMessageDialog displays a message dialog. In the example
the statement: JOptionPane.showMessageDialog( null, "The sum is " + sum, "Sum of Two
Integers", JOptionPane.PLAIN_MESSAGE ); is a call to the message dialog.
Container
Most GUIs are not composed of option panes; they are too limited. Instead, typical GUI
applications include containers such as frames , windows, panels that can hold other components.
A container is an object that holds components; it also governs their positions, sizes, and
resizing behavior.
In general, all containers have the following public methods:
public void add(Component comp)
public void add(Component comp, Object info)
Adds a component to the container, possibly giving extra information about where to
place it.
public void remove(Component comp)
Removes the given component from the container.
public void setLayout(LayoutManager mgr)
Uses the given layout manager to position the components in the container.
public void validate()
You should call this if you change the contents of a container that is already on the
screen, to make it re-do its layout.
import java.awt.*;
GUI Programming
import javax.swing.*;
public class SimpleFrame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setForeground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(new Point(10, 50));
frame.setSize(new Dimension(300, 120));
frame.setTitle("A frame");
frame.setVisible(true);
}
}
labelFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
labelFrame.setSize(260, 180);
labelFrame.setVisible(true);
}
}
LAYOUT MANAGERS
When building a GUI, you must attach each GUI component to a container, such as a window
created with a JFrame.
Also, you typically must decide where to position each GUI component, known as specifying the
layout. Java provides several layout managers that can help you position components.
A layout manager is an object contained inside frames and other graphical containers that
decides the position and size of the components inside the container.
Following is the list of commonly used layouts while designing GUI using AWT.
The FlowLayout is the default layout. It layout the components in a directional flow.
3 The components are placed on a container from left to right in the order in which they’re
added. When no more components can fit on the current line, they continue to display
left to right on the next line. If the container is resized, a FlowLayout reflows the
components, possibly with fewer or more rows based on the new container width.
4 GridLayout
GUI Programming
5 This is the most flexible layout manager class. The object of GridBagLayout aligns
the component vertically, horizontally, or along their baseline without requiring the
components of the same size.
GroupLayout
6
The GroupLayout hierarchically groups the components in order to position them in
a Container.
SpringLayout
7
A SpringLayout positions the children of its associated container according to a set
of constraints.
import java.awt.*;
import javax.swing.*;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(320, 75));
frame.setTitle("Flow layout");
frame.setLayout(new FlowLayout());// set the layout
frame.add(new JLabel("Type your ZIP Code: "));
frame.add(new JTextField(5));
frame.add(new JButton("Submit"));
frame.setVisible(true);
}
}
Example 6: GridLayout
import java.awt.*;
import javax.swing.*;
public class GridLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI Programming
Example 7: BorderLayout
import java.awt.*;
import javax.swing.*;
public class BorderLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(210, 200));
frame.setTitle("Run for the border");
frame.setLayout(new BorderLayout());
frame.add(new JButton("north"), BorderLayout.NORTH);
frame.add(new JButton("south"), BorderLayout.SOUTH);
frame.add(new JButton("west"), BorderLayout.WEST);
frame.add(new JButton("east"), BorderLayout.EAST);
frame.add(new JButton("center"), BorderLayout.CENTER);
frame.setVisible(true);
}
}
What is an Event?
GUI Building is Event Driven. Change in the state of an object is known as Event, i.e., event
describes the change in the state of the source. Events are generated as a result of user interaction
with the graphical user interface components. For example, clicking on a button, moving the
mouse, entering a character through keyboard, selecting an item from the list, and scrolling the
page are some of activities that cause an event to occur.
The code that performs a task in response to an event is called an event handler, and the overall
process of responding to events is known as event handling
GUI Programming
Types of Event
The events can be broadly classified into two categories −
Foreground Events − These events require direct interaction of the user. They are
generated as consequences of a person interacting with the graphical components in the
Graphical User Interface. For example, clicking on a button, moving the mouse, entering
a character through keyboard, selecting an item from list, scrolling the page, etc.
Background Events − these events do not require the interaction of the end user.
Operating system interrupts, hardware or software failure, timer expiration, and operation
completion are some examples of background events.
Event Classes
Event classes represent the event. Java provides various Event classes. The classes are availed to
programs by importing java.awt. event or javax.swing.event packages. The following are some
of the event classes.
EventObject Class
It is the root class from which all event state objects are derived. This class is defined in java.util
package.
Object getSource() that returns the object that fired the event.
All Events are constructed with a reference to the object, the source, that is logically deemed to
be the object upon which the Event in question initially occurred upon.
InputEvent
3
The InputEvent class is the root event class for all component-level input events.
KeyEvent
4
On entering the character the Key event is generated.
MouseEvent
5
This event indicates a mouse action occurred in a component.
WindowEvent
6
The object of this class represents the change in the state of a window.
AdjustmentEvent
7
The object of this class represents the adjustment event emitted by Adjustable objects.
ComponentEvent
8
The object of this class represents the change in the state of a window.
ContainerEvent
9
The object of this class represents the change in the state of a window.
MouseMotionEvent
10
The object of this class represents the change in the state of a window.
PaintEvent
11
The object of this class represents the change in the state of a window.
Java uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events.
GUI Programming
1) Define and set up the components. The components are the source objects on
which events occur. For example a Button is a source object for action event.
2) Create listener objects. Listeners are objects which are notified whenever a
certain event happens. The listener is responsible for generating a response to an
event.
3) Set up the relationships between the listeners and the components which
generate events of interest. This is called registering the event.
4) Define what happens in response to each event. This is event handling proper
Note
2. Components that generate events of type xxEvent have a method called addxxListener (eg.
Eg button.addActionListener(listener);
3. An interface defines the methods that will be used to deliver xxEvents. The interface is called
4. The methods which deliver events of type xxEvent have names with the pattern xx<verb> (eg
actionPerformed, mouseDragged, )
5. If the interface defines more than a few methodsan adapter class is provided. (ActionListener
doesn't have an adapter because it has only one mehtod. WindowAdapter is an example adapter
class.) An adapter class is a convenience class provided for interfaces with more than a few
methods
// create a frame
frame.setLayout(new FlowLayout());
frame.add(but1);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(null,"Button Clicked");
Java allows you to declare classes inside other classes—these are called nested classes.
Nested classes can be static or non-static. Non-static nested classes are called inner
classes and are frequently used to implement event handlers.
As with other class members, inner classes can be declared public, protected or private.
Since event handlers tend to be specific to the application in which they’re defined,
they’re often implemented as private inner classes or as anonymous inner classes.
mport javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public CourseGUI()
science.setBackground (Color.blue);
arts.setBackground (Color.red);
sports.setBackground (Color.magenta);
group.add (science);
group.add (arts);
group.add (sports);
science.addActionListener (listener);
arts.addActionListener (listener);
sports.addActionListener (listener);
primary.add (science);
GUI Programming
primary.add (arts);
primary.add (sports);
primary.add (course);
primary.setBackground (Color.green);
//frame.add(getPanel());
//frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
//frame.setVisible(true);
return primary;
if(source == science)
GUI Programming
course.setText (sc);
else
if(source == arts)
course.setText (art);
else
course.setText (sprt);
optionFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
optionFrame.getContentPane().add (gui.getPanel());
optionFrame.setVisible(true);
In this example the inner class OptionListener implements interface ActionListener and
declares the only method in that interface—actionPerformed. This method specifies the tasks to
perform when an ActionEvent occurs. When the button is pushed, the JButton object invokes
the actionPerformed method, passing it an ActionEvent .
An anonymous inner class—an inner class that’s declared without a name and typically
appears inside a method declaration. As with other inner classes, an anonymous inner
class can access its top-level class’s members. However, an anonymous inner class has
limited access to the local variables of the method in which it’s declared.
Since an anonymous inner class has no name, one object of the class must be created at
the point where the class is declared.
SWING Adapters
An adapter class provides the default implementation of all methods in an event listener
interface. Adapter classes are very useful when you want to process only few of the events that
are handled by a particular event listener interface. Adapters are abstract classes for receiving
various events. The methods in these classes are empty. These classes exist as convenience
for creating listener objects.
You can define a new class by extending one of the adapter classes and implement only those
events relevant to you. -
Since EventListener interface has only one method, it does not have an adapter class.
Events related to the mouse are separated into mouse events and mouse motion events.
GUI Programming
Mouse Events:
To satisfy the implementation of a listener interface, empty methods must be provided for
unused events since a class that implements an interface must implements all its methods.
A better approach is to extend the MouseAdapter class by overriding the method or methods of
interest and ignoring the rest.
Note the Adapter can also be implemented as anonymous or inner class. See example 1