SlideShare a Scribd company logo
1 of 72
Graphical User
Interface
Components: Part 1
Chapter 11
2
What You Will Learn
 Swing Components
 Event handling
 Mouse event handling
3
Graphical User Interface (GUI)
 Gives program distinctive “look” and “feel”
 Provides users with basic level of familiarity
 Built from GUI components (controls,
widgets, etc.)
o User interacts with GUI component via mouse,
keyboard, etc
 Check out this visual index of components
4
Netscape Window With GUI
Components
menu barbutton combo boxmenus
scroll bars
5
Dialog Boxes
 Used by applications to interact with the user
 Provided by Java’s JOptionPane class
o Contains input dialogs and message dialogs
 View example program, Figure 11.2
Title BarTitle Bar
Prompt to
user
Prompt to
user
Text field
which allows
user input
Text field
which allows
user input
When user clicks OK,
dialog box dismissed
When user clicks OK,
dialog box dismissed
6
Dialog Boxes
 Note icon
 Other icons available
Message dialog type Icon Description
ERROR_MESSAGE A dialog that indicates an error to the user.
INFORMATION_MESSAGE A dialog with an informational message to the
user.
WARNING_MESSAGE A dialog warning the user of a potential
problem.
QUESTION_MESSAGE A dialog that poses a question to the user. This
dialog normally requires a response, such as
clicking a Yes or a No button.
PLAIN_MESSAGE no icon A dialog that contains a message, but no icon.
7
Some Basic GUI Components
Component Description
JLabel Displays uneditable text or icons.
JTextField Enables user to enter data from the keyboard. Can also be used to
display editable or uneditable text.
JButton Triggers an event when clicked with the mouse.
JCheckBox Specifies an option that can be selected or not selected.
JComboBox Provides a drop-down list of items from which the user can make a
selection by clicking an item or possibly by typing into the box.
JList Provides a list of items from which the user can make a selection by
clicking on any item in the list. Multiple elements can be selected.
JPanel Provides an area in which components can be placed and organized.
Can also be used as a drawing area for graphics.
8
Overview
 Swing GUI components
o Declared in package javax.swing
o Most are pure Java components
o Part of the Java Foundation Classes (JFC)
 Abstract Window Toolkit (AWT)
o Precursor to Swing
o Declared in package java.awt
o Does not provide consistent, cross-platform look-
and-feel
9
Lightweight
vs. Heavyweight
Lightweight components
o Not tied directly to GUI components supported
by underlying platform
Heavyweight components
o Tied directly to the local platform
o AWT components
o Some Swing components
10
Superclasses of Swing’s
Lightweight GUI Components
Class Component
o (package java.awt)
o Subclass of Object
o Declares many behaviors and attributes common
to GUI components
11
Superclasses of Swing’s
Lightweight GUI Components
Class Container
o (package java.awt)
o Subclass of Component
o Organizes Components
12
Superclasses of Swing’s
Lightweight GUI Components
Class JComponent
o (package javax.swing)
o Subclass of Container
o Superclass of all lightweight Swing components
13
Common Lightweight Component
Features
 Pluggable look-and-feel
o customize the appearance of components
 Shortcut keys
o mnemonics
 Common event-handling capabilities
 Brief description of component’s purpose
o tool tips
 Support for localization
14
Displaying Text and Images in a
Window
Class JFrame
o Most windows are an instance or subclass of this
class
o Provides title bar
o Provides min, max, close buttons
Label
o Text instructions or information stating the
purpose of each component
o Created with class JLabel
15
Three Parts of a GUI Application
1. Components that make up the Graphical
User Interface
2. Listeners that receive the events and
respond to them
3. Application code that does useful work for
the user
16
Events Generated by Swing
Components
Act that results in the event Listener type
User clicks a button, presses Return
while typing in a text field, or chooses a
menu item
ActionListener
User closes a frame (main window) WindowListener
User presses a mouse button while the
cursor is over a component
MouseListener
User moves the mouse over a
component
MouseMotionListener
Component becomes visible ComponentListener
Component gets the keyboard focus FocusListener
Table or list selection changes ListSelectionListener
17
Events Generated by Swing
Components
 Each event is represented by an object
o Object gives information about the event
o Identifies the event source.
 Event sources are typically components,
o Other kinds of objects can also be event sources.
 Each event source can have multiple listeners
registered on it.
o Conversely, a
single listener can
register with
multiple event sources.
18
JLabel
 Label
o Provide text on GUI
o Defined with class JLabel
o Can display:
 Single line of read-only text
 Image
 Text and image
 View Figure 11.6
o Note uses of the JLabel Class
19
Creating and Attaching label1
Method setToolTipText of class
JComponent
o Specifies the tool tip
Method add of class Container
o Adds a component to a container
20
Creating and Attaching label2
Interface Icon
o Can be added to a JLabel with the setIcon
method
o Implemented by class ImageIcon
21
Creating and Attaching label2
Interface SwingConstants
o Declares a set of common integer constants
such as those used to set the alignment of
components
o Can be used with methods
setHorizontalAlignment and
setVerticalAlignment
22
Creating and Attaching label3
Other JLabel methods
o getText and setText
 For setting and retrieving the text of a label
o getIcon and setIcon
 For setting and retrieving the icon displayed in the
label
o getHorizontalTextPosition and
setHorizontalTextPosition
 For setting and retrieving the horizontal position of the
text displayed in the label
23
Some basic GUI Components.
Constant Description
Horizontal-position constants
SwingConstants.LEFT Place text on the left.
SwingConstants.CENTER Place text in the center.
SwingConstants.RIGHT Place text on the right.
Vertical-position constants
SwingConstants.TOP Place text at the top.
SwingConstants.CENTER Place text in the center.
SwingConstants.BOTTOM Place text at the bottom.
24
Other JFrame Methods
 setDefaultCloseOperation
o Dictates how the application reacts when the
user clicks the close button
 setSize
o Specifies the width and height of the window
 setVisible
o Determines whether the window is displayed
(true) or not (false)
25
Event Handling
 An event occurs every time the user
o Types a character or
o Pushes a mouse button
 Any object can be notified of the event.
 That object must:
o Implement the appropriate interface
o Be registered as an event listener on the
appropriate event source.
26
Event Handling
 GUI's are event driven
o Events occur when user interacts with GUI
o e.g., moving mouse, pressing button, typing in
text field, etc.
 Class java.awt.AWTEvent
 Checkout Sun tutorial on event handling
27
Some Event Classes Of Package
java.awt.event
28
Event Handling Model
 Three parts
o Event source
 GUI component with which user interacts
o Event object
 Encapsulates information about event that occurred
o Event listener
 Receives event object when notified, then responds
 Programmer must perform two tasks
o Register event listener for event source
o Implement event-handling method (event handler)
29
Event Listener Object
 When a GUI program is running, each action
of the user generates an event
 The following are some types of events:
o Moving the mouse
o Clicking the mouse on a button
o Typing some text into a text area
 For a program to respond to an event there
must be an event listener object in the GUI
program that listens to that type of event
30
What is an Event Listener?
 An event listener is an object
o It "listens" for events from a specific GUI
component (itself an object)
 When an event is generated by the GUI
component
o A method in the listener object is invoked to
respond to the event
31
What If …?
 When there is no event listener for an event
o A program can ignore events
o If there is no listener for an event, the event is
just ignored
When a tree falls in
the forest and there's
no one present to
hear it, does it make a
sound?
32
Event-
listener
Interfaces
Of Package
java.awt.
event
33
Textfields
 JTextField
o Single-line area in which user can enter text
 JPasswordField
o Extends JTextField
o Hides characters that user enters
 View Figure 11.9, Test Program 11.10
o Illustrates capabilities of textfields
o Note help on handling number fields
34
How Event Handling Works
 You must register the event handler
o Through component’s method
addActionListener
35
How Event Handling Works
 The component knows to call
actionPerformed because …
o Event is dispatched only to listeners of
appropriate type
o Each event type has corresponding event-
listener interface
 Event ID specifies event type that occurred
36
Event Registration for
JTextField textField1
37
JButton
 Button
o Component user clicks to trigger a specific action
o Several different types
 Command buttons
 Check boxes
 Toggle buttons
 Radio buttons
o javax.swing.AbstractButton subclasses
 Command buttons are created with class JButton
 Generate ActionEvents when user clicks button
38
Swing Button Hierarchy
39
JButton Example
 View, ButtonFrame class, Figure 11.15
 Test program, Figure 11.16
 Look for
o Declaration of the buttons
o Inner class ButtonHandler which does event
handling for the button
o Call to .addActionListener(handler)
method registers buttons to receive events
o The actionPerformed() method
40
Comments on JButton
 To detect when user clicks button
o Program must have an object that implements
ActionListener interface
 Program must register object as an action
listener on the button (the event source)
o Using the addActionListener method
41
Comments on JButton
 When user clicks the button, it fires an action
event.
o Results in the invocation of the action listener's
actionPerformed method
o The only method in the ActionListener
interface
 JButtons can have a rollover icon
o Appears when mouse is positioned over a button
o Added to a JButton with method
setRolloverIcon
42
Buttons That Maintain State
Swing contains three types of state buttons
JToggleButton, JCheckBox and
JRadioButton
JCheckBox and JRadioButton are
subclasses of JToggleButton
43
JCheckBox
Contains a check box label that appears to right of
check box by default
Generates an ItemEvent when it is clicked
o ItemEvents are handled by an ItemListener
o Passed to method itemStateChanged
Method isSelected returns whether check box
is selected (true) or not (false)
View example class Figure 11.17test Figure 11.18
Things to Note:
• Declaration of JCheckBox references
• Instantiation of JCheckBox objects
• Register JCheckBox's to receive events
from CheckBoxHandler
• CheckBoxHandler invokes method
itemStateChanges
• Change JTextField font, depending on
which JCheckBox was selected
Things to Note:
• Declaration of JCheckBox references
• Instantiation of JCheckBox objects
• Register JCheckBox's to receive events
from CheckBoxHandler
• CheckBoxHandler invokes method
itemStateChanges
• Change JTextField font, depending on
which JCheckBox was selected
44
JRadioButton
 Has two states – selected and unselected
 Normally appear in a group in which only one radio
button can be selected at once
o Group maintained by a ButtonGroup object

Declares method add to add a JRadioButton to group
 Usually represents mutually exclusive options
 View RadioButtonFrame, Figure 11.19Test
program, Figure 11.20
45
Demonstration of JRadioButton
 When viewing Figure 11.19, look for the
following
o Declaration of JRadioButton references
o Group specification
o Instantiation of JRadioButton objects
o Registration of JRadioButton's to receive
events
o RadioButtonHandler invokes method
itemStateChanged
46
JComboBox
 JComboBox
o List of items from which user can select
o Also called a drop-down list
 Note features in Figure 11.21
• Instantiate JComboBox to show three Strings
from names array at a time
• Register JComboBox to receive events
• ItemListener invokes method
itemStateChanged
47
JList
 A list is a series of items
o User can select one or more items
o Single-selection vs. multiple-selection
 JList demonstration, Figure 11.23
o Note use of ColorNames array to populate JList
o Specification of SINGLE_SELECTION
o Registration of JList to receive events
o ListSelectionListener invokes method
valueChanged
o Background set according to user choice
48
Multiple-Selection Lists
 Multiple-selection list capabilities
o Select many items from Jlist
o Allows continuous range selection
 Look for the following in Figure 11.25
 Use of ColorNames array
o Specification of MULTIPLE_INTERVAL_SELECTION
option
o Use of JButton and JListCopyList method
49
Mouse Events
 Create a MouseEvent object
 Handled by MouseListeners and
MouseMotionListeners
 MouseInputListener combines the two
interfaces
 Interface MouseWheelListener declares
method mouseWheelMoved to handle
MouseWheelEvents
50
Mouse Event Handling
 Event-listener interfaces for mouse events
o MouseListener
o MouseMotionListener
o Listen for MouseEvents
 In Figure 11.28 note use of…
o Register JFrame to receive mouse events
o Methods invoked for various mouse events
 (Note that program does not seem to perform as
advertised when run under ReadyTo !!?)
51
Listener Interfaces
MouseListener and MouseMotionListener interface methods
Methods of interface MouseListener
public void mousePressed( MouseEvent event )
Called when a mouse button is pressed while the mouse cursor is on a
component.
public void mouseClicked( MouseEvent event )
Called when a mouse button is pressed and released while the mouse
cursor remains stationary on a component. This event is always
preceded by a call to mousePressed.
public void mouseReleased( MouseEvent event )
Called when a mouse button is released after being pressed. This
event is always preceded by a call to mousePressed and one or
more calls to mouseDragged.
public void mouseEntered( MouseEvent event )
Called when the mouse cursor enters the bounds of a component.
52
Listener Interfaces
MouseListener and MouseMotionListener interface methods
public void mouseExited( MouseEvent event )
Called when the mouse cursor leaves the bounds of a component.
Methods of interface MouseMotionListener
public void mouseDragged( MouseEvent event )
Called when the mouse button is pressed while the mouse cursor is on
a component and the mouse is moved while the mouse button remains
pressed. This event is always preceded by a call to mousePressed.
All drag events are sent to the component on which the user began to
drag the mouse.
public void mouseMoved( MouseEvent event )
Called when the mouse is moved when the mouse cursor is on a
component. All move events are sent to the component over which the
mouse is currently positioned.
53
Listener Interfaces
 Suppose your class directly implements
MouseListener,
o Then you must implement all five
MouseListener methods.
o Even if you care only about mouse clicks
 Methods for those events you don't care
about can have empty bodies.
o Resulting collection of empty method bodies can
make code harder to read and maintain
54
Adapter Classes
 Solution is to use adapter classes
 For example, the MouseAdapter class
implements the MouseListener interface.
 An adapter class implements empty versions
of all its interface's methods.
55
Adapter Classes
 To use an adapter
o Create a subclass of it, instead of directly
implementing a listener interface.
o By extending MouseAdapter, your class
inherits empty definitions of all five of the
methods that MouseListener contains.
56
Adapter Classes
 Characteristics of an adapter class
o Implements interface
o Provides default implementation of each interface
method
o Used when all methods in interface is not needed
Event-adapter class in java.awt.event Implements interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
57
Adapter Classes
 Example of use of an adapter class
o Figure 11.34 , the Painter program
 Note
o Registration of MouseMotionListener to
listen for window’s mouse-motion events
o Override method mouseDragged, but not
method mouseMoved
o Store coordinates where mouse was dragged,
then repaint JFrame
58
Extending MouseAdapter
 The MouseDetails.java program,
Note example, Figure 11.31
 Demonstrates
o How to determine the number of mouse clicks
o How to distinguish between different mouse
buttons
59
InputEvent Methods
 Help distinguish among
o left-,
o center- and
o right-mouse-button clicks
InputEvent method Description
isMetaDown() Returns true when the user clicks the right mouse button on a
mouse with two or three buttons. To simulate a right-mouse-
button click on a one-button mouse, the user can hold down the
Meta key on the keyboard and click the mouse button.
isAltDown() Returns true when the user clicks the middle mouse button on
a mouse with three buttons. To simulate a middle-mouse-
button click on a one- or two-button mouse, the user can press
the Alt key on the keyboard and click the only- or left-mouse
button, respectively.
60
Key Event Handling
 Interface KeyListener
 Handles key events
o Generated when keys on keyboard are pressed
and released
 KeyEvent
o Contains virtual key code that represents key
 Demonstrated in Figure 11.36
61
Layout Managers
 Layout manager capabilities
o Provided for arranging GUI components
o Provide basic layout capabilities
o Processes layout details
o Programmer can concentrate on basic “look and
feel”
o Interface LayoutManager
62
Layout Managers
 Layout manager methods
Layout manager Description
FlowLayout Default for javax.swing.JPanel. Places components sequentially
(left to right) in the order they were added. It is also possible to
specify the order of the components by using the Container method
add, which takes a Component and an integer index position as
arguments.
BorderLayout Default for JFrames (and other windows). Arranges the components
into five areas: NORTH, SOUTH, EAST, WEST and CENTER.
GridLayout Arranges the components into rows and columns.
63
FlowLayout
 Most basic layout manager
 GUI components placed in container from
left to right
 Example program, Figure 11.39
o Layout set as FlowLayout
o Note results as user presses button
64
BorderLayout
 Arranges components into five regions
o NORTH (top of container)
o SOUTH (bottom of container)
o EAST (left of container)
o WEST (right of container)
o CENTER (center of container)
 View example, Figure 11.41
65
GridLayout
 Divides container into grid of specified row
an columns
 Components are added starting at top-left
cell
o Proceed left-to-fight until row is full
 GridLayout demonstration, Figure 11.43
o Clicking buttons toggles between different
layouts
66
Panels
 Helps organize components
 Class JPanel is JComponent subclass
 May have components (and other panels)
added to them
 Panel example, Figure 11.45
67
Applying Concepts
 Suppose you wish to have a GUI which
accomplishes the following
o Enter numbers
in text boxes
o Press button
to do
calculations
68
Step By Step
 View code to create the window
 Note
o Class (program) extends JFrame
o Constructor sets up window using methods
inherited from JFrame
o Method main()instantiates class object
69
Add the Text Labels
 View additional code
 Note
o Declaration, instantiation of JLabels
o Container reference, pane
Gets handle for contentPane
o pane layout specified
o JLabels added
70
Add the Text Boxes
 View next iteration of code for adding the
JTextFields
 Note
o Declaration, instantiation of JTextFields
o Change grid layout of pane for 2 columns
o Adding to pane
71
Final Version
 View final code version
 Note
o Declaration, instantiation of buttons
o Declaration, definition, instantiation of action
handlers
 Different author, does not use inner anonymous
classes
o Add action handlers to the buttons
 Our program never actually calls the action
handlers
72
Implement an Event Handler
Every event handler requires three bits of code:
1. Code that specifies that the class either
1. Implements a listener interface or
2. Extends a class that implements a listener interface.
For example:
public class MyClass implements ActionListener {…
2. Code that registers an instance of the event
handler class as a listener upon one or more
components.
For example:
someComponent.addActionListener(instanceOfMyClass);
3. Code that implements the methods in the listener
interface.
For example:
public void actionPerformed(ActionEvent e)
{ ...//code that reacts to the action... }

More Related Content

What's hot

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
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A ReviewFernando Torres
 
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
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART IIIOXUS 20
 
Java eventhandling
Java eventhandlingJava eventhandling
Java eventhandlingArati Gadgil
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handlingteach4uin
 
Java Event Handling
Java Event HandlingJava Event Handling
Java Event HandlingShraddha
 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDrRajeshreeKhande
 
GUI (graphical user interface)
GUI (graphical user interface)GUI (graphical user interface)
GUI (graphical user interface)rishi ram khanal
 
Java awt tutorial javatpoint
Java awt tutorial   javatpointJava awt tutorial   javatpoint
Java awt tutorial javatpointRicardo Garcia
 
Unit-3 event handling
Unit-3 event handlingUnit-3 event handling
Unit-3 event handlingAmol Gaikwad
 

What's hot (20)

Awt and swing in java
Awt and swing in javaAwt and swing in java
Awt and swing in java
 
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
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
 
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
 
Java awt
Java awtJava awt
Java awt
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
 
tL19 awt
tL19 awttL19 awt
tL19 awt
 
Java eventhandling
Java eventhandlingJava eventhandling
Java eventhandling
 
Event handling in Java(part 1)
Event handling in Java(part 1)Event handling in Java(part 1)
Event handling in Java(part 1)
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handling
 
Java Event Handling
Java Event HandlingJava Event Handling
Java Event Handling
 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWT
 
Java swing
Java swingJava swing
Java swing
 
Java swing
Java swingJava swing
Java swing
 
Java swing
Java swingJava swing
Java swing
 
GUI (graphical user interface)
GUI (graphical user interface)GUI (graphical user interface)
GUI (graphical user interface)
 
Java awt tutorial javatpoint
Java awt tutorial   javatpointJava awt tutorial   javatpoint
Java awt tutorial javatpoint
 
Java Swing
Java SwingJava Swing
Java Swing
 
Ingles 2do parcial
Ingles   2do parcialIngles   2do parcial
Ingles 2do parcial
 
Unit-3 event handling
Unit-3 event handlingUnit-3 event handling
Unit-3 event handling
 

Viewers also liked

Creating GUI Component APIs in Angular and Web Components
Creating GUI Component APIs in Angular and Web ComponentsCreating GUI Component APIs in Angular and Web Components
Creating GUI Component APIs in Angular and Web ComponentsRachael L Moore
 
Gui component
Gui componentGui component
Gui componentNova ed
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2PRN USM
 
File Input & Output
File Input & OutputFile Input & Output
File Input & OutputPRN USM
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 
Graphical User Interface
Graphical User Interface Graphical User Interface
Graphical User Interface Bivek Pakuwal
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1PRN USM
 
Graphical User Interface (Gui)
Graphical User Interface (Gui)Graphical User Interface (Gui)
Graphical User Interface (Gui)Bilal Amjad
 
USER INTERFACE DESIGN PPT
USER INTERFACE DESIGN PPTUSER INTERFACE DESIGN PPT
USER INTERFACE DESIGN PPTvicci4041
 

Viewers also liked (16)

Java-Events
Java-EventsJava-Events
Java-Events
 
Creating GUI Component APIs in Angular and Web Components
Creating GUI Component APIs in Angular and Web ComponentsCreating GUI Component APIs in Angular and Web Components
Creating GUI Component APIs in Angular and Web Components
 
Gui component
Gui componentGui component
Gui component
 
Course File c++
Course File c++Course File c++
Course File c++
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
Animal Handling Program
Animal Handling ProgramAnimal Handling Program
Animal Handling Program
 
Windows
WindowsWindows
Windows
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Awt
AwtAwt
Awt
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Graphical User Interface
Graphical User Interface Graphical User Interface
Graphical User Interface
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
Graphical User Interface (Gui)
Graphical User Interface (Gui)Graphical User Interface (Gui)
Graphical User Interface (Gui)
 
USER INTERFACE DESIGN PPT
USER INTERFACE DESIGN PPTUSER INTERFACE DESIGN PPT
USER INTERFACE DESIGN PPT
 

Similar to Chapter11 graphical components

28-GUI application.pptx.pdf
28-GUI application.pptx.pdf28-GUI application.pptx.pdf
28-GUI application.pptx.pdfNguynThiThanhTho
 
Java gui event
Java gui eventJava gui event
Java gui eventSoftNutx
 
Java session11
Java session11Java session11
Java session11Niit Care
 
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
 
01 Java Is Architecture Neutral
01 Java Is Architecture Neutral01 Java Is Architecture Neutral
01 Java Is Architecture Neutralrajuglobal
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)jammiashok123
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptsharanyak0721
 
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
 
Chap - 2 - Event Handling.pptx
Chap - 2 - Event Handling.pptxChap - 2 - Event Handling.pptx
Chap - 2 - Event Handling.pptxTadeseBeyene
 
ANDROID LAB MANUAL.doc
ANDROID LAB MANUAL.docANDROID LAB MANUAL.doc
ANDROID LAB MANUAL.docPalakjaiswal43
 
Event handling
Event handlingEvent handling
Event handlingswapnac12
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in JavaAyesha Kanwal
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptxusvirat1805
 
Slot04 creating gui
Slot04 creating guiSlot04 creating gui
Slot04 creating guiViên Mai
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01JONDHLEPOLY
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Elizabeth alexander
 
event handling new.ppt
event handling new.pptevent handling new.ppt
event handling new.pptusama537223
 

Similar to Chapter11 graphical components (20)

28-GUI application.pptx.pdf
28-GUI application.pptx.pdf28-GUI application.pptx.pdf
28-GUI application.pptx.pdf
 
Java gui event
Java gui eventJava gui event
Java gui event
 
Unit 6 Java
Unit 6 JavaUnit 6 Java
Unit 6 Java
 
Java session11
Java session11Java session11
Java session11
 
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
 
01 Java Is Architecture Neutral
01 Java Is Architecture Neutral01 Java Is Architecture Neutral
01 Java Is Architecture Neutral
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
 
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
 
Chap - 2 - Event Handling.pptx
Chap - 2 - Event Handling.pptxChap - 2 - Event Handling.pptx
Chap - 2 - Event Handling.pptx
 
ANDROID LAB MANUAL.doc
ANDROID LAB MANUAL.docANDROID LAB MANUAL.doc
ANDROID LAB MANUAL.doc
 
Event handling
Event handlingEvent handling
Event handling
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 
Slot04 creating gui
Slot04 creating guiSlot04 creating gui
Slot04 creating gui
 
GUI.pdf
GUI.pdfGUI.pdf
GUI.pdf
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
event handling new.ppt
event handling new.pptevent handling new.ppt
event handling new.ppt
 

Recently uploaded

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 

Recently uploaded (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

Chapter11 graphical components

  • 2. 2 What You Will Learn  Swing Components  Event handling  Mouse event handling
  • 3. 3 Graphical User Interface (GUI)  Gives program distinctive “look” and “feel”  Provides users with basic level of familiarity  Built from GUI components (controls, widgets, etc.) o User interacts with GUI component via mouse, keyboard, etc  Check out this visual index of components
  • 4. 4 Netscape Window With GUI Components menu barbutton combo boxmenus scroll bars
  • 5. 5 Dialog Boxes  Used by applications to interact with the user  Provided by Java’s JOptionPane class o Contains input dialogs and message dialogs  View example program, Figure 11.2 Title BarTitle Bar Prompt to user Prompt to user Text field which allows user input Text field which allows user input When user clicks OK, dialog box dismissed When user clicks OK, dialog box dismissed
  • 6. 6 Dialog Boxes  Note icon  Other icons available Message dialog type Icon Description ERROR_MESSAGE A dialog that indicates an error to the user. INFORMATION_MESSAGE A dialog with an informational message to the user. WARNING_MESSAGE A dialog warning the user of a potential problem. QUESTION_MESSAGE A dialog that poses a question to the user. This dialog normally requires a response, such as clicking a Yes or a No button. PLAIN_MESSAGE no icon A dialog that contains a message, but no icon.
  • 7. 7 Some Basic GUI Components Component Description JLabel Displays uneditable text or icons. JTextField Enables user to enter data from the keyboard. Can also be used to display editable or uneditable text. JButton Triggers an event when clicked with the mouse. JCheckBox Specifies an option that can be selected or not selected. JComboBox Provides a drop-down list of items from which the user can make a selection by clicking an item or possibly by typing into the box. JList Provides a list of items from which the user can make a selection by clicking on any item in the list. Multiple elements can be selected. JPanel Provides an area in which components can be placed and organized. Can also be used as a drawing area for graphics.
  • 8. 8 Overview  Swing GUI components o Declared in package javax.swing o Most are pure Java components o Part of the Java Foundation Classes (JFC)  Abstract Window Toolkit (AWT) o Precursor to Swing o Declared in package java.awt o Does not provide consistent, cross-platform look- and-feel
  • 9. 9 Lightweight vs. Heavyweight Lightweight components o Not tied directly to GUI components supported by underlying platform Heavyweight components o Tied directly to the local platform o AWT components o Some Swing components
  • 10. 10 Superclasses of Swing’s Lightweight GUI Components Class Component o (package java.awt) o Subclass of Object o Declares many behaviors and attributes common to GUI components
  • 11. 11 Superclasses of Swing’s Lightweight GUI Components Class Container o (package java.awt) o Subclass of Component o Organizes Components
  • 12. 12 Superclasses of Swing’s Lightweight GUI Components Class JComponent o (package javax.swing) o Subclass of Container o Superclass of all lightweight Swing components
  • 13. 13 Common Lightweight Component Features  Pluggable look-and-feel o customize the appearance of components  Shortcut keys o mnemonics  Common event-handling capabilities  Brief description of component’s purpose o tool tips  Support for localization
  • 14. 14 Displaying Text and Images in a Window Class JFrame o Most windows are an instance or subclass of this class o Provides title bar o Provides min, max, close buttons Label o Text instructions or information stating the purpose of each component o Created with class JLabel
  • 15. 15 Three Parts of a GUI Application 1. Components that make up the Graphical User Interface 2. Listeners that receive the events and respond to them 3. Application code that does useful work for the user
  • 16. 16 Events Generated by Swing Components Act that results in the event Listener type User clicks a button, presses Return while typing in a text field, or chooses a menu item ActionListener User closes a frame (main window) WindowListener User presses a mouse button while the cursor is over a component MouseListener User moves the mouse over a component MouseMotionListener Component becomes visible ComponentListener Component gets the keyboard focus FocusListener Table or list selection changes ListSelectionListener
  • 17. 17 Events Generated by Swing Components  Each event is represented by an object o Object gives information about the event o Identifies the event source.  Event sources are typically components, o Other kinds of objects can also be event sources.  Each event source can have multiple listeners registered on it. o Conversely, a single listener can register with multiple event sources.
  • 18. 18 JLabel  Label o Provide text on GUI o Defined with class JLabel o Can display:  Single line of read-only text  Image  Text and image  View Figure 11.6 o Note uses of the JLabel Class
  • 19. 19 Creating and Attaching label1 Method setToolTipText of class JComponent o Specifies the tool tip Method add of class Container o Adds a component to a container
  • 20. 20 Creating and Attaching label2 Interface Icon o Can be added to a JLabel with the setIcon method o Implemented by class ImageIcon
  • 21. 21 Creating and Attaching label2 Interface SwingConstants o Declares a set of common integer constants such as those used to set the alignment of components o Can be used with methods setHorizontalAlignment and setVerticalAlignment
  • 22. 22 Creating and Attaching label3 Other JLabel methods o getText and setText  For setting and retrieving the text of a label o getIcon and setIcon  For setting and retrieving the icon displayed in the label o getHorizontalTextPosition and setHorizontalTextPosition  For setting and retrieving the horizontal position of the text displayed in the label
  • 23. 23 Some basic GUI Components. Constant Description Horizontal-position constants SwingConstants.LEFT Place text on the left. SwingConstants.CENTER Place text in the center. SwingConstants.RIGHT Place text on the right. Vertical-position constants SwingConstants.TOP Place text at the top. SwingConstants.CENTER Place text in the center. SwingConstants.BOTTOM Place text at the bottom.
  • 24. 24 Other JFrame Methods  setDefaultCloseOperation o Dictates how the application reacts when the user clicks the close button  setSize o Specifies the width and height of the window  setVisible o Determines whether the window is displayed (true) or not (false)
  • 25. 25 Event Handling  An event occurs every time the user o Types a character or o Pushes a mouse button  Any object can be notified of the event.  That object must: o Implement the appropriate interface o Be registered as an event listener on the appropriate event source.
  • 26. 26 Event Handling  GUI's are event driven o Events occur when user interacts with GUI o e.g., moving mouse, pressing button, typing in text field, etc.  Class java.awt.AWTEvent  Checkout Sun tutorial on event handling
  • 27. 27 Some Event Classes Of Package java.awt.event
  • 28. 28 Event Handling Model  Three parts o Event source  GUI component with which user interacts o Event object  Encapsulates information about event that occurred o Event listener  Receives event object when notified, then responds  Programmer must perform two tasks o Register event listener for event source o Implement event-handling method (event handler)
  • 29. 29 Event Listener Object  When a GUI program is running, each action of the user generates an event  The following are some types of events: o Moving the mouse o Clicking the mouse on a button o Typing some text into a text area  For a program to respond to an event there must be an event listener object in the GUI program that listens to that type of event
  • 30. 30 What is an Event Listener?  An event listener is an object o It "listens" for events from a specific GUI component (itself an object)  When an event is generated by the GUI component o A method in the listener object is invoked to respond to the event
  • 31. 31 What If …?  When there is no event listener for an event o A program can ignore events o If there is no listener for an event, the event is just ignored When a tree falls in the forest and there's no one present to hear it, does it make a sound?
  • 33. 33 Textfields  JTextField o Single-line area in which user can enter text  JPasswordField o Extends JTextField o Hides characters that user enters  View Figure 11.9, Test Program 11.10 o Illustrates capabilities of textfields o Note help on handling number fields
  • 34. 34 How Event Handling Works  You must register the event handler o Through component’s method addActionListener
  • 35. 35 How Event Handling Works  The component knows to call actionPerformed because … o Event is dispatched only to listeners of appropriate type o Each event type has corresponding event- listener interface  Event ID specifies event type that occurred
  • 37. 37 JButton  Button o Component user clicks to trigger a specific action o Several different types  Command buttons  Check boxes  Toggle buttons  Radio buttons o javax.swing.AbstractButton subclasses  Command buttons are created with class JButton  Generate ActionEvents when user clicks button
  • 39. 39 JButton Example  View, ButtonFrame class, Figure 11.15  Test program, Figure 11.16  Look for o Declaration of the buttons o Inner class ButtonHandler which does event handling for the button o Call to .addActionListener(handler) method registers buttons to receive events o The actionPerformed() method
  • 40. 40 Comments on JButton  To detect when user clicks button o Program must have an object that implements ActionListener interface  Program must register object as an action listener on the button (the event source) o Using the addActionListener method
  • 41. 41 Comments on JButton  When user clicks the button, it fires an action event. o Results in the invocation of the action listener's actionPerformed method o The only method in the ActionListener interface  JButtons can have a rollover icon o Appears when mouse is positioned over a button o Added to a JButton with method setRolloverIcon
  • 42. 42 Buttons That Maintain State Swing contains three types of state buttons JToggleButton, JCheckBox and JRadioButton JCheckBox and JRadioButton are subclasses of JToggleButton
  • 43. 43 JCheckBox Contains a check box label that appears to right of check box by default Generates an ItemEvent when it is clicked o ItemEvents are handled by an ItemListener o Passed to method itemStateChanged Method isSelected returns whether check box is selected (true) or not (false) View example class Figure 11.17test Figure 11.18 Things to Note: • Declaration of JCheckBox references • Instantiation of JCheckBox objects • Register JCheckBox's to receive events from CheckBoxHandler • CheckBoxHandler invokes method itemStateChanges • Change JTextField font, depending on which JCheckBox was selected Things to Note: • Declaration of JCheckBox references • Instantiation of JCheckBox objects • Register JCheckBox's to receive events from CheckBoxHandler • CheckBoxHandler invokes method itemStateChanges • Change JTextField font, depending on which JCheckBox was selected
  • 44. 44 JRadioButton  Has two states – selected and unselected  Normally appear in a group in which only one radio button can be selected at once o Group maintained by a ButtonGroup object  Declares method add to add a JRadioButton to group  Usually represents mutually exclusive options  View RadioButtonFrame, Figure 11.19Test program, Figure 11.20
  • 45. 45 Demonstration of JRadioButton  When viewing Figure 11.19, look for the following o Declaration of JRadioButton references o Group specification o Instantiation of JRadioButton objects o Registration of JRadioButton's to receive events o RadioButtonHandler invokes method itemStateChanged
  • 46. 46 JComboBox  JComboBox o List of items from which user can select o Also called a drop-down list  Note features in Figure 11.21 • Instantiate JComboBox to show three Strings from names array at a time • Register JComboBox to receive events • ItemListener invokes method itemStateChanged
  • 47. 47 JList  A list is a series of items o User can select one or more items o Single-selection vs. multiple-selection  JList demonstration, Figure 11.23 o Note use of ColorNames array to populate JList o Specification of SINGLE_SELECTION o Registration of JList to receive events o ListSelectionListener invokes method valueChanged o Background set according to user choice
  • 48. 48 Multiple-Selection Lists  Multiple-selection list capabilities o Select many items from Jlist o Allows continuous range selection  Look for the following in Figure 11.25  Use of ColorNames array o Specification of MULTIPLE_INTERVAL_SELECTION option o Use of JButton and JListCopyList method
  • 49. 49 Mouse Events  Create a MouseEvent object  Handled by MouseListeners and MouseMotionListeners  MouseInputListener combines the two interfaces  Interface MouseWheelListener declares method mouseWheelMoved to handle MouseWheelEvents
  • 50. 50 Mouse Event Handling  Event-listener interfaces for mouse events o MouseListener o MouseMotionListener o Listen for MouseEvents  In Figure 11.28 note use of… o Register JFrame to receive mouse events o Methods invoked for various mouse events  (Note that program does not seem to perform as advertised when run under ReadyTo !!?)
  • 51. 51 Listener Interfaces MouseListener and MouseMotionListener interface methods Methods of interface MouseListener public void mousePressed( MouseEvent event ) Called when a mouse button is pressed while the mouse cursor is on a component. public void mouseClicked( MouseEvent event ) Called when a mouse button is pressed and released while the mouse cursor remains stationary on a component. This event is always preceded by a call to mousePressed. public void mouseReleased( MouseEvent event ) Called when a mouse button is released after being pressed. This event is always preceded by a call to mousePressed and one or more calls to mouseDragged. public void mouseEntered( MouseEvent event ) Called when the mouse cursor enters the bounds of a component.
  • 52. 52 Listener Interfaces MouseListener and MouseMotionListener interface methods public void mouseExited( MouseEvent event ) Called when the mouse cursor leaves the bounds of a component. Methods of interface MouseMotionListener public void mouseDragged( MouseEvent event ) Called when the mouse button is pressed while the mouse cursor is on a component and the mouse is moved while the mouse button remains pressed. This event is always preceded by a call to mousePressed. All drag events are sent to the component on which the user began to drag the mouse. public void mouseMoved( MouseEvent event ) Called when the mouse is moved when the mouse cursor is on a component. All move events are sent to the component over which the mouse is currently positioned.
  • 53. 53 Listener Interfaces  Suppose your class directly implements MouseListener, o Then you must implement all five MouseListener methods. o Even if you care only about mouse clicks  Methods for those events you don't care about can have empty bodies. o Resulting collection of empty method bodies can make code harder to read and maintain
  • 54. 54 Adapter Classes  Solution is to use adapter classes  For example, the MouseAdapter class implements the MouseListener interface.  An adapter class implements empty versions of all its interface's methods.
  • 55. 55 Adapter Classes  To use an adapter o Create a subclass of it, instead of directly implementing a listener interface. o By extending MouseAdapter, your class inherits empty definitions of all five of the methods that MouseListener contains.
  • 56. 56 Adapter Classes  Characteristics of an adapter class o Implements interface o Provides default implementation of each interface method o Used when all methods in interface is not needed Event-adapter class in java.awt.event Implements interface ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapter FocusListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener WindowAdapter WindowListener
  • 57. 57 Adapter Classes  Example of use of an adapter class o Figure 11.34 , the Painter program  Note o Registration of MouseMotionListener to listen for window’s mouse-motion events o Override method mouseDragged, but not method mouseMoved o Store coordinates where mouse was dragged, then repaint JFrame
  • 58. 58 Extending MouseAdapter  The MouseDetails.java program, Note example, Figure 11.31  Demonstrates o How to determine the number of mouse clicks o How to distinguish between different mouse buttons
  • 59. 59 InputEvent Methods  Help distinguish among o left-, o center- and o right-mouse-button clicks InputEvent method Description isMetaDown() Returns true when the user clicks the right mouse button on a mouse with two or three buttons. To simulate a right-mouse- button click on a one-button mouse, the user can hold down the Meta key on the keyboard and click the mouse button. isAltDown() Returns true when the user clicks the middle mouse button on a mouse with three buttons. To simulate a middle-mouse- button click on a one- or two-button mouse, the user can press the Alt key on the keyboard and click the only- or left-mouse button, respectively.
  • 60. 60 Key Event Handling  Interface KeyListener  Handles key events o Generated when keys on keyboard are pressed and released  KeyEvent o Contains virtual key code that represents key  Demonstrated in Figure 11.36
  • 61. 61 Layout Managers  Layout manager capabilities o Provided for arranging GUI components o Provide basic layout capabilities o Processes layout details o Programmer can concentrate on basic “look and feel” o Interface LayoutManager
  • 62. 62 Layout Managers  Layout manager methods Layout manager Description FlowLayout Default for javax.swing.JPanel. Places components sequentially (left to right) in the order they were added. It is also possible to specify the order of the components by using the Container method add, which takes a Component and an integer index position as arguments. BorderLayout Default for JFrames (and other windows). Arranges the components into five areas: NORTH, SOUTH, EAST, WEST and CENTER. GridLayout Arranges the components into rows and columns.
  • 63. 63 FlowLayout  Most basic layout manager  GUI components placed in container from left to right  Example program, Figure 11.39 o Layout set as FlowLayout o Note results as user presses button
  • 64. 64 BorderLayout  Arranges components into five regions o NORTH (top of container) o SOUTH (bottom of container) o EAST (left of container) o WEST (right of container) o CENTER (center of container)  View example, Figure 11.41
  • 65. 65 GridLayout  Divides container into grid of specified row an columns  Components are added starting at top-left cell o Proceed left-to-fight until row is full  GridLayout demonstration, Figure 11.43 o Clicking buttons toggles between different layouts
  • 66. 66 Panels  Helps organize components  Class JPanel is JComponent subclass  May have components (and other panels) added to them  Panel example, Figure 11.45
  • 67. 67 Applying Concepts  Suppose you wish to have a GUI which accomplishes the following o Enter numbers in text boxes o Press button to do calculations
  • 68. 68 Step By Step  View code to create the window  Note o Class (program) extends JFrame o Constructor sets up window using methods inherited from JFrame o Method main()instantiates class object
  • 69. 69 Add the Text Labels  View additional code  Note o Declaration, instantiation of JLabels o Container reference, pane Gets handle for contentPane o pane layout specified o JLabels added
  • 70. 70 Add the Text Boxes  View next iteration of code for adding the JTextFields  Note o Declaration, instantiation of JTextFields o Change grid layout of pane for 2 columns o Adding to pane
  • 71. 71 Final Version  View final code version  Note o Declaration, instantiation of buttons o Declaration, definition, instantiation of action handlers  Different author, does not use inner anonymous classes o Add action handlers to the buttons  Our program never actually calls the action handlers
  • 72. 72 Implement an Event Handler Every event handler requires three bits of code: 1. Code that specifies that the class either 1. Implements a listener interface or 2. Extends a class that implements a listener interface. For example: public class MyClass implements ActionListener {… 2. Code that registers an instance of the event handler class as a listener upon one or more components. For example: someComponent.addActionListener(instanceOfMyClass); 3. Code that implements the methods in the listener interface. For example: public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }