Download presentation
Presentation is loading. Please wait.
Published bymahi madhav Modified over 6 years ago
1
Graphical User Interface (GUI) Components: Part 1 Java How to Program, 9 th Edition Chapter 14
2
Outline 14.1 Introduction 14.2 Simple GUI Based I/O with JOptionPane 14.3 Overview of Swing Components 14.4 Displaying Text and Images in a window 14.5 Text Fields and an Introduction to Event Handling with Nested Classes 14.6 Common GUI Event Types and Listener Interfaces 14.7 How Event Handling Works 14.8 Buttons That Maintain State 14.8.1 JCheckBox 14.8.2 JRadioButton 14.9 JComboBox: Using an Anonymous Inner Class for Event Handling
3
Outline 14.10 JList 14.11 Multiple-Selection Lists 14.12 Mouse Event Handling 14.13 Adapter Classes 14.14 JPanel Sublcass for Drawing with the Mouse 14.15 Key-Event Handling 14.16 Introduction to Layout Managers 14.16.1 FlowLayout 14.16.2 BorderLayout 14.16.3 GridLayout 14.17 Using Panels to Manage More Complex Layouts 14.18 JTextArea
4
14.1 Introduction Graphical user interface (GUI) Presents a user-friendly mechanism for interacting with an application Often contains title bar, menu bar containing menus, buttons and combo boxes Built from GUI components ( Controls, widgets, etc.)
5
5 Netscape Window With GUI Components buttonmenustitle barmenu barcombo box scroll bars
6
14.2 Simple GUI-Based Input / Output with JOptionPane Dialog boxes Used by applications to interact with the user Provided by Java’s JOptionPane class Contains input dialogs and message dialogs
7
7 Outline Addition.java Show input dialog to receive first integer Show input dialog to receive second integer Show message dialog to output sum to user
8
8 Outline Addition.java Input dialog displayed by lines 10–11 Input dialog displayed by lines 12 – 13 Message dialog displayed by lines 22 – 23 Text field in which the user types a value Prompt to the user When the user clicks OK, showInputDialog returns to the program the 100 typed by the user as a String. The program must convert the String to an int title bar When the user clicks OK, the message dialog is dismissed (removed from the screen )
9
JOptionPane static constants for message dialogs.
10
14.3 Overview of Swing Components Swing GUI components Declared in package javax.swing Most are pure Java components Part of the Java Foundation Classes (JFC)
11
Some basic GUI components.
12
Swing vs. AWT Swing GUI components Declared in package javax.swing Most are pure Java components Part of the Java Foundation Classes (JFC) Abstract Window Toolkit (AWT) Precursor to Swing Declared in package java.awt Does not provide consistent, cross-platform look-and-feel
13
Lightweight vs. Heavyweight Lightweight components Not tied directly to GUI components supported by underlying platform Heavyweight components Tied directly to the local platform AWT components Some Swing components
14
Super classes of Swing’s Lightweight GUI Components Class Component (package java.awt) Subclass of Object Declares many behaviors and attributes common to GUI components
15
Super classes of Swing’s Lightweight GUI Components Class Container (package java.awt) Subclass of Component Organizes Components
16
Super classes of Swing’s Lightweight GUI Components Class JComponent (package javax.swing) Subclass of Container Superclass of all lightweight Swing components
17
Common super classes of many of the Swing components.
18
Common Lightweight Component Features Pluggable look-and-feel customize the appearance of components Shortcut keys mnemonics Common event-handling capabilities Brief description of component’s purpose tool tips Support for localization
19
14.4 Displaying Text and Images in a Window Class JFrame Most windows are an instance or subclass of this class Provides title bar Provides min, max, close buttons Label Text instructions or information stating the purpose of each component Created with class JLabel
20
JLabel Label Provide text on GUI Defined with class JLabel Can display: Single line of read-only text Image Text and image
21
Creating and Attaching label1 Method setToolTipText of class JComponent Specifies the tool tip Method add of class Container Adds a component to a container
22
Creating and Attaching label2 Interface Icon Can be added to a JLabel with the setIcon method Implemented by class ImageIcon Interface SwingConstants Declares a set of common integer constants such as those used to set the alignment of components Can be used with methods setHorizontalAlignment setVerticalAlignment
23
Creating and Attaching label3 Other JLabel methods getText and setText For setting and retrieving the text of a label getIcon and setIcon For setting and retrieving the icon displayed in the label getHorizontalTextPosition and setHorizontalTextPosition For setting and retrieving the horizontal position of the text displayed in the label
24
Some basic GUI Components.
25
Creating and Displaying a Label Frame Window Other JFrame Methods setDefaultCloseOperation Dictates how the application reacts when the user clicks the close button setSize Specifies the width and height of the window setVisible Determines whether the window is displayed (true) or not (false)
26
14.5 Text Fields and an Introduction to Event Handling with Nested Classes GUIs are event-driven A user interaction creates an event Common events are clicking a button, typing in a text field, selecting an item from a menu, closing and window and moving the mouse The event causes a call to a method called an event handler
27
14.5 Text Fields and an Introduction to Event Handling with Nested Classes Class JTextComponent Superclass of JTextField Superclass of JPasswordField Adds echo character to hide text input in component Allows user to enter text in the component when component has the application’s focus
28
Outline TextFieldFrame.java Create a new JTextField
29
Declare actionPerformed method Create a new JTextField Create a new uneditable JTextField Create a new JPasswordFieldCreate event handlerRegister event handler Create event handler class by implementing the ActionListener interface Outline TextFieldFrame.java
30
Test if the source of the event is the first text field Get text from text field Get password from password field Test if the source of the event is the second text field Test if the source of the event is the third text field Test if the source of the event is the password field Outline TextFieldFrame.java
31
Outline TextFieldTest.java
32
Outline TextFieldTest.java
33
Steps Required to Set Up Event Handling for a GUI Component Several coding steps are required for an application to respond to events Create a class for the event handler Implement an appropriate event-listener interface Register the event handler
34
Using a Nested Class to Implement an Event Handler Top-level classes Not declared within another class Nested classes Declared within another class Non-static nested classes are called inner classes Frequently used for event handling
35
Using a Nested Class to Implement an Event Handler JTextFields : Single-line area in which user can enter text JPasswordFields : Hides characters that user enters Pressing enter within either of these fields causes an ActionEvent Processed by objects that implement the ActionListener interface
36
Registering the Event Handler for Each Text Field Registering an event handler Call method addActionListener to register an ActionListener object ActionListener listens for events on the object
37
Details of Class TextFieldHandler’s actionPerformed Method Event source Component from which event originates Can be determined using method getSource Text from a JTextField can be acquired using getActionCommand Text from a JPasswordField can be acquired using getPassword
38
14.6 Common GUI Event Types and Listener Interfaces Event types All are subclasses of AWTEvent Some declared in package java.awt.event Those specific to Swing components declared in javax.swing.event
39
14.6 Common GUI Event Types and Listener Interfaces Delegation event model Event source is the component with which user interacts Event object is created and contains information about the event that happened Event listener is notified when an event happens
40
Event Handling GUI's are event driven Events occur when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc. Class java.awt.AWTEvent
41
Event Handling Model Three parts Event source GUI component with which user interacts Event object Encapsulates information about event that occurred Event listener Receives event object when notified, then responds Programmer must perform two tasks Register event listener for event source Implement event-handling method (event handler)
42
Some event classes of package java.awt.event.
43
Event Listener An event listener is an object It "listens" for events from a specific GUI component (itself an object) When an event is generated by the GUI component A method in the listener object is invoked to respond to the event
44
Some common event-listener interfaces of package java.awt.event.
45
14.7 How Event Handling Works You must register the event handler Through component’s method addActionListener The component knows to call actionPerformed because … Event is dispatched only to listeners of appropriate type Each event type has corresponding event-listener interface Event ID specifies event type that occurred
46
Event Registration for JTextField textField1
47
14.8 JButtons Button Component user clicks to trigger a specific action Several different types Command buttons Check boxes Toggle buttons Radio buttons javax.swing.AbstractButton subclasses Command buttons are created with class JButton Generate ActionEvents when user clicks button
48
Swing Button Hierarchy
49
Comments on JButton To detect when user clicks button Program must have an object that implements ActionListener interface Program must register object as an action listener on the button (the event source) Using the add ActionListener method
50
Comments on JButton When user clicks the button, it fires an action event. Results in the invocation of the action listener's actionPerformed method The only method in the ActionListener interface JButtons can have a rollover icon Appears when mouse is positioned over a button Added to a JButton with method setRolloverIcon
51
Buttons That Maintain State Swing contains three types of state buttons JToggleButton, JCheckBox and JRadioButton JCheckBox and JRadioButton are subclasses of JToggleButton
52
Outline ButtonTest.java
53
14.8.1 JCheckBox JCheckBox Contains a check box label that appears to right of check box by default Generates an ItemEvent when it is clicked ItemEvents are handled by an ItemListener Passed to method itemStateChanged Method isSelected returns whether check box is selected (true) or not (false)
54
Outline CheckBoxTest.java
55
14.8.2 JRadioButton JRadioButton Has two states – selected and unselected Normally appear in a group in which only one radio button can be selected at once Group maintained by a ButtonGroup object Declares method add to add a JRadioButton to group Usually represents mutually exclusive options
56
Outline RadioButtonTest.java
57
14.9 JComboBox and Using an Anonymous Inner Class for Event Handling Combo box Also called a drop-down list Implemented by class JComboBox Each item in the list has an index setMaximumRowCount sets the maximum number of rows shown at once JComboBox provides a scrollbar and up and down arrows to traverse list Register JComboBox to receive events ItemListener invokes method itemStateChanged
58
Using an Anonymous Inner Class for Event Handling Anonymous inner class Special form of inner class Declared without a name Typically appears inside a method call Has limited access to local variables
59
Outline ComboBoxTest.java Scrollbar to scroll through the items in the list scroll arrowsscroll box
60
14.10 JList List Displays a series of items from which the user may select one or more items Implemented by class JList Allows for single-selection lists or multiple-selection lists A ListSelectionEvent occurs when an item is selected Handled by a ListSelectionListener and passed to method valueChanged
61
Outline ListTest.java
62
14.11 Multiple-Selection Lists Multiple-selection list capabilities Enables users to select many items Single interval selection allows only a continuous range of items Multiple interval selection allows any set of elements to be selected
63
MultipleSelectionTest.java Outline
64
14.12 Mouse Event Handling Mouse events Create a MouseEvent object Handled by MouseListeners and MouseMotionListeners MouseInputListener combines the two interfaces Interface MouseWheelListener declares method mouseWheelMoved to handle MouseWheelEvents
65
MouseListener and MouseMotionListener interface methods.
67
MouseTrackerFrame.java Outline
68
14.13 Adapter Classes Adapter class Implements event listener interface Provides default implementation for all event-handling methods To use an adapter Create a subclass of it, instead of directly implementing a listener interface.
69
Extending MouseAdapter MouseAdapter Adapter class for MouseListener and MouseMotionListener interfaces Extending class allows you to override only the methods you wish to use Characteristics of an adapter class Implements interface Provides default implementation of each interface method Used when all methods in interface is not needed
70
Event-adapter classes and the interfaces they implement in package java.awt.event.
71
InputEvent Methods Help distinguish among left-, center- and right-mouse-button clicks
72
MouseDetails.java Outline
73
14.14 JPanel Sublcass for Drawing with the Mouse Overriding class JPanel Provides a dedicated drawing area Input Event methods that help distinguish among left-, center- and right-mouse-button clicks.
74
Method paintComponent Draws on a Swing component Overriding method allows you to create custom drawings Must call superclass method first when overridden
75
Defining the Custom Drawing Area Customized subclass of JPanel Provides custom drawing area Class Graphics is used to draw on Swing components Class Point represents an x-y coordinate
76
Outline Painter.java Create instance of custom drawing panel
77
14.15 Key-Event Handling interface KeyListener Handles key events Generated when keys on keyboard are pressed and released Declares methods keyPressed, keyReleased and keyTyped KeyEvent Contains virtual key code that represents key.
78
Outline KeyDemo.java
79
14.16 Introduction to Layout Managers Layout managers Provided to arrange GUI components in a container Provide basic layout capabilities Implement the interface LayoutManager Layout manager methods
80
14.16.1 FlowLayout FlowLayout Simplest layout manager Components are placed left to right in order they are added Components can be left aligned, centered or right aligned
81
Outline FlowLayoutDemo.java
82
14.16.2 BorderLayout BorderLayout Arranges components into five regions – north, south, east, west and center Implements interface LayoutManager2 Provides horizontal gap spacing and vertical gap spacing Arranges components into five regions NORTH (top of container) SOUTH (bottom of container) EAST (left of container) WEST (right of container) CENTER (center of container)
83
Outline BorderLayoutDemo.java
84
14.16.3 GridLayout GridLayout Divides container into a grid of specified row an columns Every component has the same width and height
85
Outline GridLayoutDemo.java
86
14.17 Using Panels to Manage More Complex Layouts Complex GUIs often require multiple panels to arrange their components properly Panels Helps organize components Class JPanel is JComponent subclass May have components (and other panels) added to them
87
Outline PanelDemo.java
88
14.18 JTextArea JTextArea Provides an area for manipulating multiple lines of text Box container Subclass of Container Uses a BoxLayout layout manager
89
Outline TextAreaDemo.java
90
JScrollPane Scrollbar Policies JScrollPane has scrollbar policies Horizontal policies Always (HORIZONTAL_SCROLLBAR_ALWAYS) As needed (HORIZONTAL_SCROLLBAR_AS_NEEDED) Never (HORIZONTAL_SCROLLBAR_NEVER) Vertical policies Always (VERTICAL_SCROLLBAR_ALWAYS) As needed (VERTICAL_SCROLLBAR_AS_NEEDED) Never (VERTICAL_SCROLLBAR_NEVER)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.