Graphical User Interface (GUI) Components: Part 1 Java How to Program, 9 th Edition Chapter 14.

Slides:



Advertisements
Similar presentations
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Advertisements

CS18000: Problem Solving and Object-Oriented Programming.
Graphic User Interfaces Layout Managers Event Handling.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
 2005 Pearson Education, Inc. All rights reserved GUI Components: Part 1.
Graphical User Interfaces (GUIs) GUI: An application that uses graphical objects to interact with users GUI applications consist of: –Events: A user or.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Graphical User Interface Components: Part 1
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 - Event Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
Dale Roberts GUI Programming using Java - Introduction Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
Graphical User Interface Components: Part 1 Chapter 11.
 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.
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.
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.
AGDER COLLEGEFACULTY OF ENGINEERING & SCIENCE GUI Components ikt403 – Object-Oriented Software Development.
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 Chapter 13 CSCI CSCI 1302 – Creating User Interfaces2 Outline Introduction Common Features of Swing GUI Components Buttons.
Creating User Interfaces Event-Driven Programming.
Basics of GUI Programming Chapter 11 and Chapter 22.
Java Programming, Second Edition Chapter Thirteen Understanding Swing Components.
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.
Computer Science [3] Java Programming II - Laboratory Course Lab 4 -1 : Introduction to Graphical user interface GUI Components Faculty of Engineering.
 Many event-listener interfaces contain multiple methods.  An adapter class implements an interface and provides a default implementation (with an empty.
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.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
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.
A Quick Java Swing Tutorial
GUI Programming using Java - Event Handling
CompSci 230 S Programming Techniques
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 (pronounced "gooey")
A Quick Java Swing Tutorial
Ellen Walker Hiram College
Chap 7. Building Java Graphical User Interfaces
Chapter 13: Advanced GUIs and Graphics
Graphical User Interfaces -- Introduction
MSIS670: Object-Oriented Software Engineering
Timer class and inner classes
IFS410: Advanced Analysis and Design
A Quick Java Swing Tutorial
Advanced Programming in Java
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Graphical User Interface (GUI) Components: Part 1 Java How to Program, 9 th Edition Chapter 14

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 JCheckBox JRadioButton 14.9 JComboBox: Using an Anonymous Inner Class for Event Handling

Outline JList Multiple-Selection Lists Mouse Event Handling Adapter Classes JPanel Sublcass for Drawing with the Mouse Key-Event Handling Introduction to Layout Managers FlowLayout BorderLayout GridLayout Using Panels to Manage More Complex Layouts JTextArea

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 Netscape Window With GUI Components buttonmenustitle barmenu barcombo box scroll bars

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 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 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 )

JOptionPane static constants for message dialogs.

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)

Some basic GUI components.

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

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

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

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

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

Common super classes of many of the 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

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

JLabel Label Provide text on GUI Defined with class JLabel Can display: Single line of read-only text Image Text and image

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

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.

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)

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

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

Outline TextFieldFrame.java Create a new JTextField

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

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

Outline TextFieldTest.java

Outline TextFieldTest.java

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

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

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

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

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

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

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

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

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)

Some event classes of package java.awt.event.

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

Some common event-listener interfaces of package java.awt.event.

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

Event Registration for JTextField textField1

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

Swing Button Hierarchy

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

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

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

Outline ButtonTest.java

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)

Outline CheckBoxTest.java

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

Outline RadioButtonTest.java

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

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

Outline ComboBoxTest.java Scrollbar to scroll through the items in the list scroll arrowsscroll box

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

Outline ListTest.java

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

MultipleSelectionTest.java Outline

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

MouseListener and MouseMotionListener interface methods.

MouseTrackerFrame.java Outline

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.

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

Event-adapter classes and the interfaces they implement in package java.awt.event.

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

MouseDetails.java Outline

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.

Method paintComponent Draws on a Swing component Overriding method allows you to create custom drawings Must call superclass method first when overridden

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

Outline Painter.java Create instance of custom drawing panel

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.

Outline KeyDemo.java

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

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

Outline FlowLayoutDemo.java

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)

Outline BorderLayoutDemo.java

GridLayout GridLayout Divides container into a grid of specified row an columns Every component has the same width and height

Outline GridLayoutDemo.java

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

Outline PanelDemo.java

14.18 JTextArea JTextArea Provides an area for manipulating multiple lines of text Box container Subclass of Container Uses a BoxLayout layout manager

Outline TextAreaDemo.java

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)