SlideShare a Scribd company logo
1 of 51
Download to read offline
LECTURE 11: GUI APPLICATION
o GUI
o GUI Components
o Event Handler
PLAN
2
o A graphical user interface (GUI) presents a user-friendly
mechanism for interacting with an application.
– Pronounced “GOO-ee”
– Gives an application a distinctive “look” and “feel.”
– Consistent, intuitive user-interface components give users a
sense of familiarity
– Learn new applications more quickly and use them more
productively.
Introduction
3
o Built from GUI components.
– Sometimes called controls or widgets—short for window gadgets.
o User interacts via the mouse, the keyboard or another form of input,
such as voice recognition.
o IDEs
– Provide GUI design tools to specify a component’s exact size and
location in a visual manner by using the mouse.
– Generates the GUI code for you.
– Greatly simplifies creating GUIs, but each IDE has different
capabilities and generates different code.
Introduction (cont.)
4
GUI Example
5
o Swing GUI components located in package javax.swing.
o Abstract Window Toolkit (AWT) in package java.awt is another set of
GUI components in Java.
– When a Java application with an AWT GUI executes on different
Java platforms, the application’s GUI components display differently
on each platform.
o Together, the appearance and the way in which the user interacts with
the application are known as that application’s look-and-feel.
o Swing GUI components allow you to specify a uniform look-and-feel for
your application across all platforms or to use each platform’s custom
look-and-feel.
Overview of Swing Components
6
o Most Swing components are not tied to actual GUI components of
the underlying platform.
– Known as lightweight components.
o AWT components are tied to the local platform and are called
heavyweight components, because they rely on the local
platform’s windowing system to determine their functionality and
their look-and-feel.
o Several Swing components are heavyweight components.
Overview of Swing Components
7
Using JOptionPane for Output
import javax.swing.*;
. . .
JOptionPane.showMessageDialog( null, “I Love Java” );
8
Using JOptionPane for Output - 2
import javax.swing.*;
. . .
JOptionPane.showMessageDialog( null, “onentwonthree”
);
//place newline n to display multiple lines of output
9
JOptionPane for Input
import javax.swing.*;
. . .
String inputstr =
JOptionPane.showInputDialog( null, “What is your name?” );
10
JOptionPane static constants
11
o Most windows that can contain Swing GUI components are instances of
class JFrame or a subclass of JFrame.
o JFrame is an indirect subclass of class java.awt.Window
o Provides the basic attributes and behaviors of a window
– a title bar at the top
– buttons to minimize, maximize and close the window
o Most of our examples will consist of two classes
– a subclass of JFrame that demonstrates new GUI concepts
– an application class in which main creates and displays the
application’s primary window.
Displaying Text and Images in a Window
12
o To create a customized frame window, we define a subclass of the
JFrame class.
o The JFrame class contains rudimentary functionalities to support
features found in any frame window.
Subclassing JFrame
13
Creating a Plain JFrame
import javax.swing.*;
class DefaultJFrame {
public static void main( String[] args ) {
JFrame defaultJFrame;
defaultJFrame = new JFrame();
defaultJFrame.setVisible(true);
}
}
14
o To define a subclass of another class, we declare the subclass
with the reserved word extends.
Creating a Subclass of JFrame
import javax.swing.*;
class Ch7JFrameSubclass1 extends JFrame {
. . .
}
15
o The content pane is where we put GUI objects such as buttons,
labels, scroll bars, and others.
o We access the content pane by calling the frame’s
getContentPane method.
The Content Pane of a Frame
This gray area is the
content pane of this
frame.
16
o Here's how we can change the background color of a content
pane to blue:
Changing the Background Color
Container contentPane = getContentPane();
contentPane.setBackground(Color.BLUE);
17
•There are two ways to put GUI objects on the content
pane of a frame:
– Use a layout manager
• FlowLayout
• BorderLayout
• GridLayout
– Use absolute positioning
• null layout manager
Placing GUI Objects on a Frame
18
o A JButton object a GUI component that represents a pushbutton.
o Here's an example of how we place a button with FlowLayout.
Placing a Button
contentPane.setLayout( new FlowLayout());
okButton = new JButton("OK");
cancelButton = new JButton("CANCEL");
contentPane.add(okButton);
contentPane.add(cancelButton);
19
o Many IDEs provide GUI design tools in which you can specify the
exact size and location of a component
o IDE generates the GUI code for you
o Greatly simplifies GUI creation
o To ensure that this book’s examples can be used with any IDE, we
did not use an IDE to create the GUI code
o We use Java’s layout managers in our GUI examples
IDE Help for GUI Desgin
20
o The layout manager determines how the GUI components are
added to the container (such as the content pane of a frame)
o Among the many different layout managers, the common ones are
– FlowLayout
– BorderLayout
– GridLayout
Layout Managers
21
o In using this layout, GUI componentsare placed in left-to-right
order.
– When the component does not fit on the same line, left-to-right
placement continues on the next line.
o As a default, components on each line are centered.
o When the frame containing the component is resized, the
placement of components is adjusted accordingly.
FlowLayout
22
o This shows the placement of five buttons by using FlowLayout.
FlowLayout Sample
23
o This layout manager divides the container into five regions: center,
north, south, east, and west.
o The north and south regions expand or shrink in height only
o The east and west regions expand or shrink in width only
o The center region expands or shrinks on both height and width.
o Not all regions have to be occupied.
BorderLayout
24
BorderLayout Sample
25
o This layout manager placesGUI components on equal-size N by M
grids.
o Components are placed in top-to-bottom, left-to-right order.
o The number of rows and columns remains the same after the
frame is resized, but the width and height of each region will
change.
GridLayout
26
GridLayout Sample
27
o An action involving a GUI object, such as clicking a button, is
called an event.
o The mechanism to process events is called event handling.
o The event-handling model of Java is based on the concept known
as the delegation-based event model.
o With this model, event handling is implemented by two types of
objects:
– event source objects
– event listener objects
Event Handling
28
o An event source is a GUI object where an event occurs. We say
an event source generates events.
o Buttons, text boxes, list boxes, and menus are common event
sources in GUI-based applications.
o Although possible, we do not, under normal circumstances, define
our own event sources when writing GUI-based applications.
Event Source Objects
29
o An event listener object is an object that includes a method that
gets executed in response to the generated events.
o A listener must be associated, or registered, to a source, so it can
be notified when the source generates events.
Event Listener Objects
30
Connecting Source and
Listener
JButton Handler
event source event listener
notify
register
A listener must be registered to a event source. Once
registered, it will get notified when the event source
generates events.
31
o Registration and notification are specific to event types
• Mouse listener handles mouse events
• Item listener handles item selection events
• and so forth
o Among the different types of events, the action event is the most
common.
– Clicking on a button generates an action event
– Selecting a menu item generates an action event
– and so forth
o Action events are generated by action event sources and handled by
action event listeners.
Event Types
32
Handling Action Events
JButton Button
Handler
action event
source
action event
listener
actionPerformed
addActionListener
JButton button = new JButton("OK");
ButtonHandler handler = new ButtonHandler( );
button.addActionListener(handler);
33
o A Java interface includes only constants and abstract methods.
o An abstract method has only the method header, or prototype.
There is no method body. You cannot create an instance of a Java
interface.
o A Java interface specifies a behavior.
o A class implements an interface by providing the method body to
the abstract methods stated in the interface.
o Any class can implement the interface.
The Java Interface
34
o When we call the addActionListener method of an event source,
we must pass an instance of a class that implements the
ActionListener interface.
o The ActionListener interface includes one method named
actionPerformed.
o A class that implements the ActionListener interface must
therefore provide the method body of actionPerformed.
o Since actionPerformed is the method that will be called when an
action event is generated, this is the place where we put a code
we want to be executed in response to the generated events.
ActionListener Interface
35
The ButtonHandler Class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ButtonHandler implements ActionListener {
. . .
public void actionPerformed(ActionEvent event) {
JButton clickedButton = (JButton) event.getSource();
JRootPane rootPane = clickedButton.getRootPane
( );
Frame frame = (JFrame) rootPane.getParent();
frame.setTitle("You clicked " + clickedButton.getText
());
}
}
36
o Instead of defining a separate event listener such as
ButtonHandler, it is much more common to have an object that
contains the event sources be a listener.
– Example: We make this frame a listener of the action events of
the buttons it contains.
Container as Event Listener
event source
event listener
37
ButtonFrameHandlerDemo
. . .
class JButtonFrameHandlerDemo extends JFrame implements ActionListener {
. . .
public void actionPerformed(ActionEvent event) {
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
setTitle("You clicked " + buttonText);
}
}
38
o The Swing GUI classes JLabel, JTextField, and JTextArea deal
with text.
o A JLabel object displays uneditable text (or image).
o A JTextField object allows the user to enter a single line of text.
o A JTextArea object allows the user to enter multiple lines of text. It
can also be used for displaying multiple lines of uneditable text.
GUI Classes for Handling Text
39
o We use a JTextField object to accept a single line to text from a
user. An action event is generated when the user presses the
ENTER key.
o The getText method of JTextField is used to retrieve the text that
the user entered.
JTextField
JTextField input = new JTextField( );
input.addActionListener(eventListener);
contentPane.add(input);
40
o We use a JLabel object to display a label.
o A label can be a text or an image.
o When creating an image label, we pass ImageIcon object instead
of a string.
JLabel
JLabel textLabel = new JLabel("Please enter your name");
contentPane.add(textLabel);
JLabel imgLabel = new JLabel(new ImageIcon("cat.gif"));
contentPane.add(imgLabel);
41
Ch14TextFrame2
JLabel
(with an image)
JLabel
(with a text)
JTextField
42
o We use a JTextArea object to display or allow the user to enter
multiple lines of text.
o The setText method assigns the text to a JTextArea, replacing the
current content.
o The append method appends the text to the current text.
JTextArea
JTextArea textArea
= new JTextArea( );
. . .
textArea.setText("Hellon");
textArea.append("the lost ");
textArea.append("world");
Hello
the lost world
JTextArea
43
Demo
44
o By default a JTextArea does not have any scroll bars. To add
scroll bars, we place a JTextArea in a JScrollPane object.
Adding Scroll Bars to
JTextArea
JTextArea textArea = new JTextArea();
. . .
JScrollPane scrollText = new JScrollPane(textArea);
. . .
contentPane.add(scrollText);
45
Demo
46
• JCheckBox
• JRadioButton
• JComboBox
• JList
• JSlider
Other Common GUI Components
47
o The javax.swing package contains three menu-related classes:
JMenuBar, JMenu, and JMenuItem.
o JMenuBar is a bar where the menus are placed. There is one
menu bar per frame.
o JMenu (such as File or Edit) is a group of menu choices.
JMenuBar may include many JMenu objects.
o JMenuItem (such as Copy, Cut, or Paste) is an individual menu
choice in a JMenu object.
o Only the JMenuItem objects generate events.
Menus
48
Menu Components
Edit View Help
JMenuBar Edit View Help
File
JMenu
JMenuItem
separator
49
o Create a JMenuBar object and attach it to a frame.
o Create a JMenu object.
o Create JMenuItem objects and add them to the JMenu object.
o Attach the JMenu object to the JMenuBar object.
Sequence for Creating Menus
50
• Demo a GUI application with several components working
together, loading data from file to manage
Demo
51

More Related Content

Similar to LECTURE 11: GUI APPLICATION COMPONENTS

Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Elizabeth alexander
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptsharanyak0721
 
SWING USING JAVA WITH VARIOUS COMPONENTS
SWING USING  JAVA WITH VARIOUS COMPONENTSSWING USING  JAVA WITH VARIOUS COMPONENTS
SWING USING JAVA WITH VARIOUS COMPONENTSbharathiv53
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Javasuraj pandey
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892renuka gavli
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in javaAdil Mehmoood
 
222066369 clad-study-guide
222066369 clad-study-guide222066369 clad-study-guide
222066369 clad-study-guidehomeworkping9
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01Ankit Dubey
 
Basic iOS Training with SWIFT - Part 3
Basic iOS Training with SWIFT - Part 3Basic iOS Training with SWIFT - Part 3
Basic iOS Training with SWIFT - Part 3Manoj Ellappan
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Javababak danyal
 
Synapseindia dotnet development chapter 14 event-driven programming
Synapseindia dotnet development  chapter 14 event-driven programmingSynapseindia dotnet development  chapter 14 event-driven programming
Synapseindia dotnet development chapter 14 event-driven programmingSynapseindiappsdevelopment
 
Advanced java lab swing mvc awt
Advanced java lab swing mvc awtAdvanced java lab swing mvc awt
Advanced java lab swing mvc awtvishal choudhary
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024nehakumari0xf
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024kashyapneha2809
 
Graphical User Interface (Gui)
Graphical User Interface (Gui)Graphical User Interface (Gui)
Graphical User Interface (Gui)Bilal Amjad
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01JONDHLEPOLY
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptxusvirat1805
 

Similar to LECTURE 11: GUI APPLICATION COMPONENTS (20)

Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
 
SWING USING JAVA WITH VARIOUS COMPONENTS
SWING USING  JAVA WITH VARIOUS COMPONENTSSWING USING  JAVA WITH VARIOUS COMPONENTS
SWING USING JAVA WITH VARIOUS COMPONENTS
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Java
 
Gui
GuiGui
Gui
 
iOS Development (Part 2)
iOS Development (Part 2)iOS Development (Part 2)
iOS Development (Part 2)
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
222066369 clad-study-guide
222066369 clad-study-guide222066369 clad-study-guide
222066369 clad-study-guide
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
 
Basic iOS Training with SWIFT - Part 3
Basic iOS Training with SWIFT - Part 3Basic iOS Training with SWIFT - Part 3
Basic iOS Training with SWIFT - Part 3
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Java
 
Synapseindia dotnet development chapter 14 event-driven programming
Synapseindia dotnet development  chapter 14 event-driven programmingSynapseindia dotnet development  chapter 14 event-driven programming
Synapseindia dotnet development chapter 14 event-driven programming
 
Advanced java lab swing mvc awt
Advanced java lab swing mvc awtAdvanced java lab swing mvc awt
Advanced java lab swing mvc awt
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
 
JAVA (UNIT 5)
JAVA (UNIT 5)JAVA (UNIT 5)
JAVA (UNIT 5)
 
Graphical User Interface (Gui)
Graphical User Interface (Gui)Graphical User Interface (Gui)
Graphical User Interface (Gui)
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 

Recently uploaded

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 

Recently uploaded (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 

LECTURE 11: GUI APPLICATION COMPONENTS

  • 1. LECTURE 11: GUI APPLICATION
  • 2. o GUI o GUI Components o Event Handler PLAN 2
  • 3. o A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an application. – Pronounced “GOO-ee” – Gives an application a distinctive “look” and “feel.” – Consistent, intuitive user-interface components give users a sense of familiarity – Learn new applications more quickly and use them more productively. Introduction 3
  • 4. o Built from GUI components. – Sometimes called controls or widgets—short for window gadgets. o User interacts via the mouse, the keyboard or another form of input, such as voice recognition. o IDEs – Provide GUI design tools to specify a component’s exact size and location in a visual manner by using the mouse. – Generates the GUI code for you. – Greatly simplifies creating GUIs, but each IDE has different capabilities and generates different code. Introduction (cont.) 4
  • 6. o Swing GUI components located in package javax.swing. o Abstract Window Toolkit (AWT) in package java.awt is another set of GUI components in Java. – When a Java application with an AWT GUI executes on different Java platforms, the application’s GUI components display differently on each platform. o Together, the appearance and the way in which the user interacts with the application are known as that application’s look-and-feel. o Swing GUI components allow you to specify a uniform look-and-feel for your application across all platforms or to use each platform’s custom look-and-feel. Overview of Swing Components 6
  • 7. o Most Swing components are not tied to actual GUI components of the underlying platform. – Known as lightweight components. o AWT components are tied to the local platform and are called heavyweight components, because they rely on the local platform’s windowing system to determine their functionality and their look-and-feel. o Several Swing components are heavyweight components. Overview of Swing Components 7
  • 8. Using JOptionPane for Output import javax.swing.*; . . . JOptionPane.showMessageDialog( null, “I Love Java” ); 8
  • 9. Using JOptionPane for Output - 2 import javax.swing.*; . . . JOptionPane.showMessageDialog( null, “onentwonthree” ); //place newline n to display multiple lines of output 9
  • 10. JOptionPane for Input import javax.swing.*; . . . String inputstr = JOptionPane.showInputDialog( null, “What is your name?” ); 10
  • 12. o Most windows that can contain Swing GUI components are instances of class JFrame or a subclass of JFrame. o JFrame is an indirect subclass of class java.awt.Window o Provides the basic attributes and behaviors of a window – a title bar at the top – buttons to minimize, maximize and close the window o Most of our examples will consist of two classes – a subclass of JFrame that demonstrates new GUI concepts – an application class in which main creates and displays the application’s primary window. Displaying Text and Images in a Window 12
  • 13. o To create a customized frame window, we define a subclass of the JFrame class. o The JFrame class contains rudimentary functionalities to support features found in any frame window. Subclassing JFrame 13
  • 14. Creating a Plain JFrame import javax.swing.*; class DefaultJFrame { public static void main( String[] args ) { JFrame defaultJFrame; defaultJFrame = new JFrame(); defaultJFrame.setVisible(true); } } 14
  • 15. o To define a subclass of another class, we declare the subclass with the reserved word extends. Creating a Subclass of JFrame import javax.swing.*; class Ch7JFrameSubclass1 extends JFrame { . . . } 15
  • 16. o The content pane is where we put GUI objects such as buttons, labels, scroll bars, and others. o We access the content pane by calling the frame’s getContentPane method. The Content Pane of a Frame This gray area is the content pane of this frame. 16
  • 17. o Here's how we can change the background color of a content pane to blue: Changing the Background Color Container contentPane = getContentPane(); contentPane.setBackground(Color.BLUE); 17
  • 18. •There are two ways to put GUI objects on the content pane of a frame: – Use a layout manager • FlowLayout • BorderLayout • GridLayout – Use absolute positioning • null layout manager Placing GUI Objects on a Frame 18
  • 19. o A JButton object a GUI component that represents a pushbutton. o Here's an example of how we place a button with FlowLayout. Placing a Button contentPane.setLayout( new FlowLayout()); okButton = new JButton("OK"); cancelButton = new JButton("CANCEL"); contentPane.add(okButton); contentPane.add(cancelButton); 19
  • 20. o Many IDEs provide GUI design tools in which you can specify the exact size and location of a component o IDE generates the GUI code for you o Greatly simplifies GUI creation o To ensure that this book’s examples can be used with any IDE, we did not use an IDE to create the GUI code o We use Java’s layout managers in our GUI examples IDE Help for GUI Desgin 20
  • 21. o The layout manager determines how the GUI components are added to the container (such as the content pane of a frame) o Among the many different layout managers, the common ones are – FlowLayout – BorderLayout – GridLayout Layout Managers 21
  • 22. o In using this layout, GUI componentsare placed in left-to-right order. – When the component does not fit on the same line, left-to-right placement continues on the next line. o As a default, components on each line are centered. o When the frame containing the component is resized, the placement of components is adjusted accordingly. FlowLayout 22
  • 23. o This shows the placement of five buttons by using FlowLayout. FlowLayout Sample 23
  • 24. o This layout manager divides the container into five regions: center, north, south, east, and west. o The north and south regions expand or shrink in height only o The east and west regions expand or shrink in width only o The center region expands or shrinks on both height and width. o Not all regions have to be occupied. BorderLayout 24
  • 26. o This layout manager placesGUI components on equal-size N by M grids. o Components are placed in top-to-bottom, left-to-right order. o The number of rows and columns remains the same after the frame is resized, but the width and height of each region will change. GridLayout 26
  • 28. o An action involving a GUI object, such as clicking a button, is called an event. o The mechanism to process events is called event handling. o The event-handling model of Java is based on the concept known as the delegation-based event model. o With this model, event handling is implemented by two types of objects: – event source objects – event listener objects Event Handling 28
  • 29. o An event source is a GUI object where an event occurs. We say an event source generates events. o Buttons, text boxes, list boxes, and menus are common event sources in GUI-based applications. o Although possible, we do not, under normal circumstances, define our own event sources when writing GUI-based applications. Event Source Objects 29
  • 30. o An event listener object is an object that includes a method that gets executed in response to the generated events. o A listener must be associated, or registered, to a source, so it can be notified when the source generates events. Event Listener Objects 30
  • 31. Connecting Source and Listener JButton Handler event source event listener notify register A listener must be registered to a event source. Once registered, it will get notified when the event source generates events. 31
  • 32. o Registration and notification are specific to event types • Mouse listener handles mouse events • Item listener handles item selection events • and so forth o Among the different types of events, the action event is the most common. – Clicking on a button generates an action event – Selecting a menu item generates an action event – and so forth o Action events are generated by action event sources and handled by action event listeners. Event Types 32
  • 33. Handling Action Events JButton Button Handler action event source action event listener actionPerformed addActionListener JButton button = new JButton("OK"); ButtonHandler handler = new ButtonHandler( ); button.addActionListener(handler); 33
  • 34. o A Java interface includes only constants and abstract methods. o An abstract method has only the method header, or prototype. There is no method body. You cannot create an instance of a Java interface. o A Java interface specifies a behavior. o A class implements an interface by providing the method body to the abstract methods stated in the interface. o Any class can implement the interface. The Java Interface 34
  • 35. o When we call the addActionListener method of an event source, we must pass an instance of a class that implements the ActionListener interface. o The ActionListener interface includes one method named actionPerformed. o A class that implements the ActionListener interface must therefore provide the method body of actionPerformed. o Since actionPerformed is the method that will be called when an action event is generated, this is the place where we put a code we want to be executed in response to the generated events. ActionListener Interface 35
  • 36. The ButtonHandler Class import javax.swing.*; import java.awt.*; import java.awt.event.*; class ButtonHandler implements ActionListener { . . . public void actionPerformed(ActionEvent event) { JButton clickedButton = (JButton) event.getSource(); JRootPane rootPane = clickedButton.getRootPane ( ); Frame frame = (JFrame) rootPane.getParent(); frame.setTitle("You clicked " + clickedButton.getText ()); } } 36
  • 37. o Instead of defining a separate event listener such as ButtonHandler, it is much more common to have an object that contains the event sources be a listener. – Example: We make this frame a listener of the action events of the buttons it contains. Container as Event Listener event source event listener 37
  • 38. ButtonFrameHandlerDemo . . . class JButtonFrameHandlerDemo extends JFrame implements ActionListener { . . . public void actionPerformed(ActionEvent event) { JButton clickedButton = (JButton) event.getSource(); String buttonText = clickedButton.getText(); setTitle("You clicked " + buttonText); } } 38
  • 39. o The Swing GUI classes JLabel, JTextField, and JTextArea deal with text. o A JLabel object displays uneditable text (or image). o A JTextField object allows the user to enter a single line of text. o A JTextArea object allows the user to enter multiple lines of text. It can also be used for displaying multiple lines of uneditable text. GUI Classes for Handling Text 39
  • 40. o We use a JTextField object to accept a single line to text from a user. An action event is generated when the user presses the ENTER key. o The getText method of JTextField is used to retrieve the text that the user entered. JTextField JTextField input = new JTextField( ); input.addActionListener(eventListener); contentPane.add(input); 40
  • 41. o We use a JLabel object to display a label. o A label can be a text or an image. o When creating an image label, we pass ImageIcon object instead of a string. JLabel JLabel textLabel = new JLabel("Please enter your name"); contentPane.add(textLabel); JLabel imgLabel = new JLabel(new ImageIcon("cat.gif")); contentPane.add(imgLabel); 41
  • 43. o We use a JTextArea object to display or allow the user to enter multiple lines of text. o The setText method assigns the text to a JTextArea, replacing the current content. o The append method appends the text to the current text. JTextArea JTextArea textArea = new JTextArea( ); . . . textArea.setText("Hellon"); textArea.append("the lost "); textArea.append("world"); Hello the lost world JTextArea 43
  • 45. o By default a JTextArea does not have any scroll bars. To add scroll bars, we place a JTextArea in a JScrollPane object. Adding Scroll Bars to JTextArea JTextArea textArea = new JTextArea(); . . . JScrollPane scrollText = new JScrollPane(textArea); . . . contentPane.add(scrollText); 45
  • 47. • JCheckBox • JRadioButton • JComboBox • JList • JSlider Other Common GUI Components 47
  • 48. o The javax.swing package contains three menu-related classes: JMenuBar, JMenu, and JMenuItem. o JMenuBar is a bar where the menus are placed. There is one menu bar per frame. o JMenu (such as File or Edit) is a group of menu choices. JMenuBar may include many JMenu objects. o JMenuItem (such as Copy, Cut, or Paste) is an individual menu choice in a JMenu object. o Only the JMenuItem objects generate events. Menus 48
  • 49. Menu Components Edit View Help JMenuBar Edit View Help File JMenu JMenuItem separator 49
  • 50. o Create a JMenuBar object and attach it to a frame. o Create a JMenu object. o Create JMenuItem objects and add them to the JMenu object. o Attach the JMenu object to the JMenuBar object. Sequence for Creating Menus 50
  • 51. • Demo a GUI application with several components working together, loading data from file to manage Demo 51