Injibara University
College of Engineering and Technology
Department of Software Engineering
Advanced Programming (SEng6132)
Chapter One: AWT and Swing
3/23/2025 1
Contents
▪ Introduction
▪ Simple GUI-Based I/O with JOptionPane
▪ Concepts of AWT and Swing
▪ Event Handling
3/23/2025 2
Introduction
▪ Computer programs can use a console or a GUI to interact with the user
▪ Console applications use text-based program output and keyboard entered user input.
▪ GUIs use a graphical window or windows that provide interaction with the user.
▪ GUI’s accept input from both the keyboard and a mouse, and a variety of other input devices.
▪ A graphical user interface (GUI) presents a user-friendly mechanism for interaction.
▪ It 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—in other
languages)
3
Simple GUI-Based I/O with JOptionPane
▪ The following simple addition application uses two input dialogs to obtain integers from the
user and a message dialog to display the sum of the integers the user enters.
import [Link];
public class Addition {
public static void main( String args[] ) {
String firstNum = [Link]("Enter first integer“);
int number1 = [Link](firstNum);
String secondNum = [Link]("Enter second integer");
int number2 = [Link](secondNum);
int sum = number1 + number2; // add numbers
[Link]( null, "The sum is " + sum,
"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE);
}} 4
Cont …
▪ Java’s JOptionPane class (package [Link]) provides prepackaged dialog boxes for both input and
output.
▪ These dialogs are displayed by invoking static JOptionPane methods.
✓showInputDialog method displays an input dialog using the method’s String argument ("Enter
first integer") as a prompt . It has a text box and two buttons ok and Cancel
✓showMessageDialog method is used to display a message dialog containing the sum.
▪ The first argument helps the Java application determine where to position the dialog box.
▪ The value null indicates that the dialog should appear in the center.
▪ It can also be used to specify that the dialog should appear centered over a particular window of
the computer screen.
5
Cont. …
❖The second argument is the message to display, in this case, the result of
concatenating the String "The sum is " and the value of sum.
❖The third argument—"Sum of Two Integers"—represents the string that should appear in the dialog’s
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.
Other possible constants are: ERROR_MESSAGE, INFORMATION_MESSAGE,
WARNING_MESSAGE, QUESTION_MESSAGE.
❖Class JOptionPane provides several overloaded versions of methods showInputDialog and
showMessageDialog, as well as methods that display other dialog types.
6
AWT vs Swing
• Java has two GUI packages, the original Abstract Windows Toolkit (AWT) and the newer Swing.
• When java was introduced, the GUI classes were bundled in a library known as Abstract
Windows Toolkit(AWT).
• AWT (Abstract Window Toolkit) is java’s original set of classes for building GUIs.
Uses peer components of the OS; heavyweight.
Uses the native operating system's window routines so the visual effect is dependent on the
run-time system platform.
7
Cont. …
For every platform on which Java runs, the AWT components are automatically
mapped to the platform-specific components through their respective agents,
known as peers.
Not truly portable: looks different and lays out inconsistently on different OSs.
The application's GUI components display differently on each platform.
It is adequate for many applications but it is difficult to build an attractive GUI.
8
Cont. …
Swing: is designed to solve AWT’s problems (since Java 2 ).
99% java; lightweight components: drawing of components is done in java.
Swing GUI components allow you to specify a uniform look-and-feel for your application
across all platforms.
Lays out consistently on all OS.
Much bigger set of built-in components.
Uses AWT event handling.
9
Cont. …
• Swing is built “on top of” AWT, so you need to import AWT and use a few
things from it.
• Swing is bigger and slower.
• Swing is more flexible and better looking.
• Swing and AWT are incompatible:- you can use either, but you can’t mix them.
10
Cont. …
• Basic components/controls are practically the same in both
AWT: Button b = new Button ("OK");
Swing: JButton b = new JButton("OK");
• Swing gives far more options for everything (buttons with pictures on them, etc.)
• AWT classes are contained inside package [Link] while
• Swing classes are located in package [Link].
11
GUI Classes
• The GUI classes can be classified into three groups:
Container class,
Helper class, and
Component classes.
Container classes
• A GUI is built by putting components/controls into containers.
• Container is used to group components.
• Frames, Panels and applets are examples of containers.
• Important container classes are JFrame, JApplet, and JPanel.
12
Container Classes
JFrame
✓A resizable, movable window with title bar and close button.
✓Usually it contains JPanels.
✓It is a container that holds other Swing user-interface components in Java GUI application.
JPanel
✓A region internal to a JFrame or another JPanel.
✓Used for grouping components together.
✓Optionally bounded by a visible border.
✓Lives inside some enclosing Container.
✓Panels can be nested.
13
✓we can place panels inside a container that includes a panel.
Cont.…
✓The terms “pane” and “panel” are used interchangeably in Java.
✓If a frame is a window, a pane is the glass.
✓Panes hold a window’s GUI components.
✓Every frame has at least one pane, the default “Content Pane”.
JApplet
✓Is a subclass of Applet
14
Component class
GUI Components or Controls (also known as "widgets")
• Are the basic user interface elements the user interacts with labels, buttons, textFields,
textArea, comboBox
• The visual arrangement of the components depends on the container's layout.
• When the user does something to a component, the component's listener is sent an event.
15
Cont …
• Input Components
• JButton, JRadioButtons, JCheckBox
• JTextField
• JTextArea
• JMenuBar, JMenu, JMenuItem
• JSlider
• JComboBox
• List (Jlist)
• Information Display Components
• JLabel
• Progress bars (JProgressBar)
• Choosers
• File chooser (JFileChooser)
• Color chooser (JColorChooser)
16
Cont …
▪ More complex displays
• Tables (JTable)
• Trees (JTree)
• Formatted Text
▪ Every GUI components has
• Properties
JButton
• Methods
• Events
17
GUI Helper Classes
They are used to describe the properties of GUI components such as graphics context, colors,
fonts, and dimension.
Graphics
✓ Is an abstract class that provides a graphical context for drawings strings, lines, and simple
shapes.
Color:
✓ Deals with the colors of GUI components.
For example:- you can specify background colors in components like Jframe and Jpanel.
You can specify colors of lines, shapes etc.
18
Cont …
Font
✓ Specify fonts for the text and drawings on GUI components.
Example:- You can specify the font type(e.g. SansSerif), style (e.g. bold), and size(e.g. 24
points) for the text on the button.
Font f=new Font();
LayoutManager
✓ Is an interface whose instances specify how components are arranged in a
container.
✓The helper classes are in the [Link] package.
• The Swing components do not replace all the classes in AWT, only AWT GUI components
classes (e.g. Button, TextField, TextArea).
• The AWT helper classes remain unchanged.
19
Steps to build a GUI
1. Make a Container:– you need to create either a frame or an applet to hold the user-
interface components.
2. Create some more Components (buttons, text areas, etc.).
3. Add your Components to your display area: Choose a layout manager.
4. Attach Listeners to your Components: interacting with a component causes an Event
to occur.
20
Creating a Frames
Frame
• Is an independent window that has decorations such as a border, a title and buttons for
closing, minimizing and maximizing the window.
• Frame is a window that is not contained inside another window.
• Can be moved around on the screen independently of any other GUI windows.
• Applications with a GUI typically use at least one frame.
• Frame is the basis to contain other user interface components in Java GUI applications.
21
Cont. …
• The JFrame class can be used to create windows.
JFrame frame = new Jframe();
JFrame class Constructor summary
JFrame()
Constructs a new frame with no title and it is initially
invisible.
JFrame(String title)
Creates a new, initially invisible Frame with the specified title.
22
Cont …
JFrame Class Methods
setBounds(int x, int y, int width,Int height)
✓ Specifies the size of the frame and the location of the upper left corner.
✓ This puts the upper left corner at location (x, y), where x the number of pixels from the left
of the screen and y is the number from the top of the screen.
❑ public void setDefaultCloseOperation(int mode): is used to specify one of several options for the
close button.
Use one of the following constants to specify your choice:
oJFrame.EXIT_ON_CLOSE:- Exit the application.
oJFrame.HIDE_ON_CLOSE:- Hide the frame, but keep the application running.
oJFrame.DO_NOTHING_ON_CLOSE:- Ignore the click.
23
Cont …
import [Link].*;
public class JFrameSample {
public static void main(String[] args) {
JFrame frame = new JFrame(“First JFrame");
[Link](400, 300);
[Link](null);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}}
24
Cont …
• The frame is not display until the [Link](true) method is invoked.
• [Link](400, 300)specifies that the frame is 400 pixels wide and 300 pixels
high.
• If the setSize and setVisible methods are both defined in the Component class, they
are inherited by the JFrame class.
• Invoking setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) tells the
program to terminate when the frame is closed.
25
Cont …
✓ If you forget to call setDefaultCloseOperation() you will get
JFrame.HIDE_ON_CLOSE by default.
• Thus the program does not terminate when the frame is closed.
• The setTitle(String text) method is defined in the [Link] class.
• Since JFrame is subclass of Frame, you can use it to set a title for an object of JFrame.
26
Event
▪ Event: change in the state of an object.
▪ Events are generated as 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 a list, scrolling the page are the activities that cause an event to happen.
▪ In the event handling process, there are three important players.
✓ Event,
✓ Event Source, and
✓ Event Listener (or Handler)
27
3/23/2025
Event and Event Source
▪ An event can be defined as a type of signal to the program that something has happened.
▪ The event is generated by external user actions such as mouse movements, mouse clicks, and
keystrokes, or by the operating system, such as a timer.
▪ Event is represented by an Event class (e.g., ActionEvent, ComponentEvent , FocusEvent,
KeyEvent, MouseEvent, etc).
28
3/23/2025
Event Classes
ActionEvent ContainerEvent
AdjustmentEvent FocusEvent MouseEvent
EventObject AWTEvent ComponentEvent InputEvent
ItemEvent PaintEvent KeyEvent
TextEvent WindowEvent
ListSelectionEvent
29
3/23/2025
Event Classes
30
3/23/2025 30
Event and Event Source…..
▪ An event is created when an event occurs (i.e., user interacts with a GUI component).
▪ An event is an instance (object) of an event class.
▪ The component on which an event is fired or generated is called the source object or source
component(Event source).
▪ Example A button is the source object for a button-clicking action event.(i.e. an ActionEvent
Object is generated. )
▪ An event object contains all necessary information about the event that has occurred
✓ Type of event that has occurred
✓ Source of the event using getSource() instance method in the EventObject class.
31
3/23/2025 31
Cont. ….
32
3/23/2025 32
Listeners, Registrations, and Handling Events
▪ Java uses Event-Delegation Model for event handling: a source object fires an event, and an
object interested in the event handles the event.
▪ The latter object is called a Event Listener ( or handler).
▪ In java, there are different Event Listener interface to create listener object to handle every
type of GUI events.
33
3/23/2025 33
Cont. …
▪ Two things are needed for an object to be a listener for an event on the source object.
▪ The listener object must be an instance of the corresponding event- listener interface to ensure
that the listener has the correct method for processing the event.
▪ The listener interface is usually named XListener for XEvent, with exception of
MouseMotionListener.
▪ Example:
▪ The corresponding listener interface for ActionEvent is ActionListener; each listener for
ActionEvent should implement the ActionListener interface.
3/23/2025 34
Events, Event Listener, and Listener Methods
Event Class Listener Interface Listener Methods (Handlers)
ActionEvent ActionListener actionPerformed(ActionEvent)
ItemEvent ItemListener itemStateChanged(ItemEvent)
WindowEvent WindowListener windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
ContainerEvent ContainerListener componentAdded(ContainerEvent)
componentRemoved(ContainerEvent) MouseEventMouseListener
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseClicked(MouseEvent)
mouseExited(MouseEvent)
mouseEntered(MouseEvent)
KeyEvent KeyListener keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTypeed(KeyEvent)
3/23/2025 35
Listeners, Registrations, and Handling Events…
2. The listener object must be registered by the source object.
• To register listener object, we have a registration methods which are
dependent on the event type.
Example: For ActionEvent, the method is addActionListener.
• In general, the method is named addXListener for XEvent.
3/23/2025 36
Steps for Creating GUI Applications with Event Handling
1. Create a GUI class
✓ Describes and displays the appearance of your GUI application
2. Create Event Listener class (a class implementing the appropriate listener interface)
✓ Override all methods of the appropriate listener interface
✓ Describe in each method how you would like the event to be handled
✓ May give empty implementations for methods you don't need
3. Register the listener object with the event source
✓ The object is an instantiation of the listener class in step 2
✓ Use the add<Type>Listener method of the event source
37
3/23/2025 37
Cont …
Example 1:
import [Link].*;
import [Link].*;
import [Link].*;
public class SimpleEventDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
JButton jbtOK = new JButton("OK");
[Link](new FlowLayout());
[Link](jbtOK);
OKListener listener = new OKListener();
[Link](listener);
[Link]("SimpleEventDemo");
[Link](200, 200);
[Link](true);
}
}
3/23/2025 38
Cont …
class OKListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
[Link]("OK button is Clicked");
} } // end of class OKListener
3/23/2025 39
Cont …
Example 2
import [Link];
import [Link].*;
import [Link].*;
public class MyEvent extends JFrame {
JButton b1;
public MyEvent(){
super("Window Title: Event Handling");
b1 = new JButton("Click Me");
add(b1, [Link]);
ButtonListener listen = new ButtonListener();
[Link](listen);
setSize(200,200);
setVisible(true);
}
3/23/2025 40
Cont. …
public static void main (String arg[]){
MyEvent event = new MyEvent();
}
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
JButton source = (JButton)[Link]();
[Link]("Button Has Been Clicked, ...!");
}
}
3/23/2025 41
import [Link].*;
import [Link].*;
import [Link].*;
public class MouseEventsDemo extends JFrame implements MouseListener {
JTextArea ta;
JScrollPane scrollPane;
public MouseEventsDemo(String title){
super(title);
ta = new JTextArea("start", 10, 20);
[Link](false);
scrollPane = new JScrollPane(ta);
// Register event listener to the event source
addMouseListener(this);
}
public void launchFrame() {// Displays GUI
add(scrollPane, [Link]);
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
3/23/2025 42
Cont …
// Implement methods of event listener interface
public void mouseClicked(MouseEvent me) {
[Link]("\nMouse clicked at "+ [Link]() + ","
+ [Link]());
}
public void mouseEntered(MouseEvent me) {
[Link]("\nMouse entered component.");
}
public void mouseExited(MouseEvent me) {
[Link]("\nMouse exited component.");
}
public void mousePressed(MouseEvent me) {
[Link]("\nMouse pressed.");
}
public void mouseReleased(MouseEvent me) {
[Link]("\nMouse released.");
}
43
3/23/2025 43
Cont …
public static void main(String args[]) {// Main method
MouseEventsDemo med =
new MouseEventsDemo("Mouse Events Demo");
[Link]();
}
}
Sample Output
3/23/2025 44
Inner Class Example
Example 1:
import [Link].*;
import [Link].*;
import [Link].*;
public class SimpleEventDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
JButton jbtOK = new JButton("OK");
[Link](new FlowLayout());
[Link](jbtOK);
OKListener listener = new OKListener();
[Link](listener);
3/23/2025 45
Cont …
[Link]("SimpleEventDemo");
[Link](null);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](200, 200);
[Link](true);
}// End of main() method
class OKListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
[Link]("It is OK");
}
} // end of class OKListener
}//end of class SimpleEventDemo
3/23/2025 46