Graphical User Interface Components: Part 1

Slides:



Advertisements
Similar presentations
Event handling and listeners What is an event? user actions and context event sources and listeners Why should my programs be event- driven? User interaction.
Advertisements

1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
CS18000: Problem Solving and Object-Oriented Programming.
Graphic User Interfaces Layout Managers Event Handling.
Fall 2007CS 225 Graphical User Interfaces Event Handling Appendix C.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Graphical User Interfaces (GUIs) GUI: An application that uses graphical objects to interact with users GUI applications consist of: –Events: A user or.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Graphic User Interfaces Part 1. Typical GUI Screen from Microsoft Word What GUI “components” can you see? –Menus? Buttons? Labels? What else? –Anything.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
GUI Programming in Java
Java Programming Chapter 10 Graphical User Interfaces.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 13 Creating User.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Dale Roberts GUI Programming using Java - Introduction Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
Graphical User Interface Components: Part 1 Chapter 11.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
 2002 Prentice Hall, Inc. All rights reserved Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
1 Unit 5 GUI Aum Amriteshwaryai Namah. 2 Overview Shall learn how to reuse the graphics classes provided by Java for constructing Graphical User Interface.
GUI Clients 1 Enterprise Applications CE00465-M Clients with Graphical User Interfaces.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Dale Roberts GUI Programming using Java - GUI Components Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
Timer class and inner classes. Processing timer events Timer is part of javax.swing helps manage activity over time Use it to set up a timer to generate.
Layout Managers Arranges and lays out the GUI components on a container.
Omer Boyaci.  GUIs are event driven.  When the user interacts with a GUI component, the interaction—known as an event—drives the program to perform.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement.
Object Oriented Programming.  Interface  Event Handling.
Swing Components. Introduction Swing – A set of GUI classes – Part of the Java's standard library –Much better than the previous library: AWT Abstract.
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
Graphical User Interface Components: Part 1 Chapter 11.
Creating User Interfaces Event-Driven Programming.
Basics of GUI Programming Chapter 11 and Chapter 22.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
 Figure illustrates a hierarchy containing many event classes from the package java.awt.event.  Used with both AWT and Swing components.  Additional.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
1 Lecture 8: User Interface Components with Swing.
Jozef Goetz Credits: Copyright  Pearson Education, Inc. All rights reserved. expanded by J. Goetz, 2016.
TENTH LECTURE Event and listener. Events and Listeners An event can be defined as a type of signal to the program that something has happened. The event.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
Dale Roberts GUI Programming using Java - Windowing Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
© Copyright by Pearson Education, Inc. All Rights Reserved. Appendix I GUI Components and Event Handling Android How to Program, 3/e.
Welcome To java
11 GUI Components: Part 1.
11 GUI Components: Part 1.
Appendix I GUI Components and Event Handling
A First Look at GUI Applications
Graphical User Interface (GUI) Components: Part 1 Java How to Program, 9 th Edition Chapter 14.
Ellen Walker Hiram College
Chap 7. Building Java Graphical User Interfaces
Chapter 13: Advanced GUIs and Graphics
Graphical User Interfaces -- Introduction
Timer class and inner classes
IFS410: Advanced Analysis and Design
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Graphical User Interface Components: Part 1 Chapter 11

What You Will Learn Swing Components Event handling Mouse event handling

Graphical User Interface (GUI) Gives program distinctive “look” and “feel” Provides users with basic level of familiarity Built from GUI components (controls, widgets, etc.) User interacts with GUI component via mouse, keyboard, etc Check out this visual index of components

Netscape Window With GUI Components menu bar button combo box menus scroll bars

Dialog Boxes Used by applications to interact with the user Provided by Java’s JOptionPane class Contains input dialogs and message dialogs View example program, Figure 11.2 Text field which allows user input Title Bar Prompt to user When user clicks OK, dialog box dismissed

Dialog Boxes Note icon Other icons available

Some Basic GUI Components

Overview Swing GUI components Abstract Window Toolkit (AWT) 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

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

Superclasses of Swing’s Lightweight GUI Components Class Component (package java.awt) Subclass of Object Declares many behaviors and attributes common to GUI components

Superclasses of Swing’s Lightweight GUI Components Class Container (package java.awt) Subclass of Component Organizes Components

Superclasses of Swing’s Lightweight GUI Components Class JComponent (package javax.swing) Subclass of Container Superclass of all lightweight Swing components

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

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

Three Parts of a GUI Application Components that make up the Graphical User Interface Listeners that receive the events and respond to them Application code that does useful work for the user

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

Events Generated by Swing Components Each event is represented by an object Object gives information about the event Identifies the event source. Event sources are typically components, Other kinds of objects can also be event sources. Each event source can have multiple listeners registered on it. Conversely, a single listener can register with multiple event sources.

JLabel Label View Figure 11.6 Provide text on GUI Defined with class JLabel Can display: Single line of read-only text Image Text and image View Figure 11.6 Note uses of the JLabel Class

Creating and Attaching label1 Method setToolTipText of class JComponent Specifies the tool tip Method add of class Container Adds a component to a container

Creating and Attaching label2 Interface Icon Can be added to a JLabel with the setIcon method Implemented by class ImageIcon

Creating and Attaching label2 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 and setVerticalAlignment

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

Some basic GUI Components.

Other JFrame Methods setDefaultCloseOperation setSize setVisible 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)

Event Handling An event occurs every time the user Types a character or Pushes a mouse button Any object can be notified of the event. That object must: Implement the appropriate interface Be registered as an event listener on the appropriate event source.

Event Handling GUI's are event driven Class java.awt.AWTEvent Events occur when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc. Class java.awt.AWTEvent Checkout Sun tutorial on event handling

Some Event Classes Of Package java.awt.event

Event Handling Model Three parts Programmer must perform two tasks 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)

Event Listener Object When a GUI program is running, each action of the user generates an event The following are some types of events: Moving the mouse Clicking the mouse on a button 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

What is an 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

What If …? When there is no event listener for an event When a tree falls in the forest and there's no one present to hear it, does it make a sound? When there is no event listener for an event A program can ignore events If there is no listener for an event, the event is just ignored

Event-listener Interfaces Of Package java.awt.event

Textfields JTextField JPasswordField Single-line area in which user can enter text JPasswordField Extends JTextField Hides characters that user enters View Figure 11.9, Test Program 11.10 Illustrates capabilities of textfields Note help on handling number fields

How Event Handling Works You must register the event handler Through component’s method addActionListener

How Event Handling Works 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

Event Registration for JTextField textField1

JButton 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

Swing Button Hierarchy

JButton Example View, ButtonFrame class, Figure 11.15 Test program, Figure 11.16 Look for Declaration of the buttons Inner class ButtonHandler which does event handling for the button Call to .addActionListener(handler) method registers buttons to receive events The actionPerformed() method

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 addActionListener method

Comments on JButton JButtons can have a rollover icon 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

Buttons That Maintain State Swing contains three types of state buttons JToggleButton, JCheckBox and JRadioButton JCheckBox and JRadioButton are subclasses of JToggleButton

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) View example class Figure 11.17 test 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

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 View RadioButtonFrame, Figure 11.19 Test program, Figure 11.20

Demonstration of JRadioButton When viewing Figure 11.19, look for the following Declaration of JRadioButton references Group specification Instantiation of JRadioButton objects Registration of JRadioButton's to receive events RadioButtonHandler invokes method itemStateChanged

JComboBox JComboBox Note features in Figure 11.21 List of items from which user can select 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

JList A list is a series of items JList demonstration, Figure 11.23 User can select one or more items Single-selection vs. multiple-selection JList demonstration, Figure 11.23 Note use of ColorNames array to populate JList Specification of SINGLE_SELECTION Registration of JList to receive events ListSelectionListener invokes method valueChanged Background set according to user choice

Multiple-Selection Lists Multiple-selection list capabilities Select many items from Jlist Allows continuous range selection Look for the following in Figure 11.25 Use of ColorNames array Specification of MULTIPLE_INTERVAL_SELECTION option Use of JButton and JListCopyList method

Mouse Events Create a MouseEvent object Handled by MouseListeners and MouseMotionListeners MouseInputListener combines the two interfaces Interface MouseWheelListener declares method mouseWheelMoved to handle MouseWheelEvents

Mouse Event Handling Event-listener interfaces for mouse events MouseListener MouseMotionListener Listen for MouseEvents In Figure 11.28 note use of… Register JFrame to receive mouse events Methods invoked for various mouse events (Note that program does not seem to perform as advertised when run under ReadyTo !!?)

Listener Interfaces

Listener Interfaces

Listener Interfaces Suppose your class directly implements MouseListener, Then you must implement all five MouseListener methods. Even if you care only about mouse clicks Methods for those events you don't care about can have empty bodies. Resulting collection of empty method bodies can make code harder to read and maintain

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.

Adapter Classes To use an adapter Create a subclass of it, instead of directly implementing a listener interface. By extending MouseAdapter, your class inherits empty definitions of all five of the methods that MouseListener contains.

Adapter Classes Characteristics of an adapter class Implements interface Provides default implementation of each interface method Used when all methods in interface is not needed

Adapter Classes Example of use of an adapter class Note Figure 11.34 , the Painter program Note Registration of MouseMotionListener to listen for window’s mouse-motion events Override method mouseDragged, but not method mouseMoved Store coordinates where mouse was dragged, then repaint JFrame

Extending MouseAdapter The MouseDetails.java program, Note example, Figure 11.31 Demonstrates How to determine the number of mouse clicks How to distinguish between different mouse buttons

InputEvent Methods Help distinguish among left-, center- and right-mouse-button clicks

Key Event Handling Interface KeyListener Handles key events KeyEvent Generated when keys on keyboard are pressed and released KeyEvent Contains virtual key code that represents key Demonstrated in Figure 11.36

Layout Managers Layout manager capabilities Provided for arranging GUI components Provide basic layout capabilities Processes layout details Programmer can concentrate on basic “look and feel” Interface LayoutManager

Layout Managers Layout manager methods

FlowLayout Most basic layout manager GUI components placed in container from left to right Example program, Figure 11.39 Layout set as FlowLayout Note results as user presses button

BorderLayout 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) View example, Figure 11.41

GridLayout Divides container into grid of specified row an columns Components are added starting at top-left cell Proceed left-to-fight until row is full GridLayout demonstration, Figure 11.43 Clicking buttons toggles between different layouts

Panels Helps organize components Class JPanel is JComponent subclass May have components (and other panels) added to them Panel example, Figure 11.45

Applying Concepts Suppose you wish to have a GUI which accomplishes the following Enter numbers in text boxes Press button to do calculations

Step By Step View code to create the window Note Class (program) extends JFrame Constructor sets up window using methods inherited from JFrame Method main()instantiates class object

Add the Text Labels View additional code Note Declaration, instantiation of JLabels Container reference, pane Gets handle for contentPane pane layout specified JLabels added

Add the Text Boxes View next iteration of code for adding the JTextFields Note Declaration, instantiation of JTextFields Change grid layout of pane for 2 columns Adding to pane

Final Version View final code version Note Declaration, instantiation of buttons Declaration, definition, instantiation of action handlers Different author, does not use inner anonymous classes Add action handlers to the buttons Our program never actually calls the action handlers

Implement an Event Handler Every event handler requires three bits of code: Code that specifies that the class either Implements a listener interface or Extends a class that implements a listener interface. For example: public class MyClass implements ActionListener {… Code that registers an instance of the event handler class as a listener upon one or more components. For example: someComponent.addActionListener(instanceOfMyClass); Code that implements the methods in the listener interface. For example: public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }