Alice in Action with Java Chapter 14 Events and GUIs.

Slides:



Advertisements
Similar presentations
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Advertisements

Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Deitel Ch 11-part 1 Java GUIs 1 Java GUIs (Deitel, Chap 14-part1) Focus: Attaching GUI components + event handling  input dialog => only one value for.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
COMP 14 Introduction to Programming Miguel A. Otaduy June 8, 2004.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 21, 2005.
1 Applets Chapter 1 To understand:  why applets are used to extend the capabilities of Web pages  how an applet is executed and know about the restrictions.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Chapter 14 Applets. 2 Knowledge Goals Understand the differing roles of applications and applets Understand how a browser operates Understand the role.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
Java Programming Chapter 10 Graphical User Interfaces.
Chapter 9: Applets Jim Burns Fall Outline Learn about applets Learn about applets Write an HTML doc to host an applet Write an HTML doc to host.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet.
Welcome to CIS 083 ! Events CIS 068.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
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: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
CIS 068 Welcome to CIS 083 ! Introduction to GUIs: JAVA Swing.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
GUI programming Graphical user interface-based programming.
Java Event Handling CSIS 3701: Advanced Object Oriented Programming.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
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.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
Java Programming: From Problem Analysis to Program Design, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 2 – Welcome Application Introduction to Graphical.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Ajmer Singh PGT(IP) JAVA IDE Programming - I. Ajmer Singh PGT(IP) GUI (Graphical User Interface) It is an interface that uses a graphic entities along.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Graphical User Interface (GUI)
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Applets. 9/04/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L12: Applets Slide 2 Applets Usually.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
GUIs & Event-Driven Programming Chapter 11 Review.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
GUIs and Events Rick Mercer.
A First Look at GUI Applications
Graphical User Interface (pronounced "gooey")
Java Programming: From Problem Analysis to Program Design,
Ellen Walker Hiram College
Chapter 13: Advanced GUIs and Graphics
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Alice in Action with Java Chapter 14 Events and GUIs

Alice in Action with Java2 Events and GUIs Event: an occurrence during program execution –Examples: mouse clicks and key presses Event handler: a mechanism that manages events –A method is written to provide responsive behavior –A method is then associated with the event Event-driven program: program directed by events Chapter goals –Write event-driven programs in Java –Build graphical user interfaces (GUIs) –Handle events generated by GUIs

Alice in Action with Java3 Introduction: Miles to Kilometers and Vice Versa Elements of user story for MilesKmsConverter –Open a window –Display two boxes: “Miles:” and “Kilometers:” –User enters numerical data into either box If Miles box is selected, program returns kilometers value If Kilometers box is selected, program returns miles value –User clicks the Close button to quit the application Storyboard: sketch that captures a program element –Example: storyboard can be used to represent a GUI Transition diagram: shows GUI’s response to events

Alice in Action with Java4 Introduction: Miles to Kilometers and Vice Versa (continued)

Alice in Action with Java5 Introduction: Miles to Kilometers and Vice Versa (continued)

Alice in Action with Java6 Introduction: Miles to Kilometers and Vice Versa (continued)

Alice in Action with Java7 Introduction: Miles to Kilometers and Vice Versa (continued) Three user events that must be handled –The user clicks the window’s Close button –The user enters a number in the “Miles:” text box –The user enters a number in the “Kilometers:” text box Java provides components to build GUIs –Example: JTextField for an input box Listener : class used to store event handlers Listeners used in MilesKmConverter program –KmsListener and MilesListener –Contain methods to handle event (provide conversion)

Alice in Action with Java8 Introduction: Miles to Kilometers and Vice Versa (continued)

Alice in Action with Java9 Introduction: Miles to Kilometers and Vice Versa (continued)

Alice in Action with Java10 Java GUI Components, Events, and Listeners Four parts to MilesKmsConverter MilesKmsConverter constructor –Lines 9-27: constructs the GUI MilesListener class –Lines 29-43: handles user events in the “Miles:” box KmsListener class –Lines 45-59: handles user events in “Kilometers:” box main() method –Lines 65-69: flow begins when the program is run

Alice in Action with Java11 The main() Method First line: call to MilesKmsConverter constructor –Builds a MilesKmsConverter object –Stores a reference to an object named self Second line: self.pack(); –Causes GUI to set itself to minimum display size Third line: self.setVisible(true); –Causes the application’s GUI to appear Role of the Java Runtime Environment (JRE) –Controls program after main() constructs objects –Polls for events, runs handlers, quits the application

Alice in Action with Java12 GUI Components javax.swing package: source of GUI components

Alice in Action with Java13 GUI Components (continued)

Alice in Action with Java14 GUI Components (continued)

Alice in Action with Java15 GUI Components (continued) javax.swing package: source of GUI components The JFrame class –Window including standard features such as title bar –Application using a GUI will first extend JFrame –MilesKmsConverter is a JFrame –Use super() to invoke one of the JFrame constructors Example: super("Miles-Kms"); The JPanel class –Corresponds to a window pane –A layout manager can be passed to one constructor

Alice in Action with Java16 GUI Components (continued) Layout managers –Determine how graphical components will be laid out –Example: GridLayout(row, col) add(component) –Message sent to existing JPanel to add components Borders –Border object adds spaces to the edge of a JPanel –Example: Miles-Kms GUI has a 5 pixel wide border The JLabel component –Used to provide a label

Alice in Action with Java17 GUI Components (continued)

Alice in Action with Java18 GUI Components (continued)

Alice in Action with Java19 GUI Components (continued)

Alice in Action with Java20 GUI Components (continued) The JTextField component –Used to build input boxes –Usually declared as an instance variable –Has a variety of constructors Content pane: graphical components appear on this A JPanel must become the JFrame ’s content pane Setting the content pane –Use the JFrame#setContentPane() method –Ex: super.setContentPane(controlPanel);

Alice in Action with Java21 GUI Components (continued) The QUIT event –Default operation of Close button is to hide a window –Default operation must be reset to quit the application Use setDefaultCloseOperation() Registering event handlers –Informs component which Listener handles an event –ActionEvent is handled by an ActionListener –Example: register an event handler with JTextField MilesListener is passed to addActionListener() addActionListener() is called against myMilesBox

Alice in Action with Java22 Events Some GUI components can generate events –Example: ActionEvent is generated in JTextField Different events are handled by different listeners –Example: KeyEvent is handled by KeyListener Java listeners are interfaces –All methods in an interface are defined by implementer MilesListener implements ActionListener –Must define the actionPerformed() method –Method handles ActionEvents from JTextField KmsListener also implements ActionListener

Alice in Action with Java23 Events (continued)

Alice in Action with Java24 Events (continued) Handling events generated by a graphical component –Identify the event generated by the component –Identify the listener used to handle the event –Define a class that implements the listener’s interface –Create class instance and register it with the component Using one ActionListener for all components –actionPerformed() gets event id with getSource() –After event identified, if statement selects response –Disadvantage: leads to complex, error prone methods Write specialized listener for each component

Alice in Action with Java25 The serialVersionUID Attribute Serializable interface –Implemented by most graphical components Two functions permitted by Serializable –Permits objects to be transmitted across a network –Permits objects to be written to or read from a file The long type named serialVersionUID –JRE uses value to determine type of object to be rebuilt –Should be defined by implementer of Serializable –Also should be set to a unique number –Absence of definition could result in compiler warning

Alice in Action with Java26 Example 2: Using Sliders and Buttons RGB color –Consists of different amounts of red, green, and blue –Range of color values: Requirements of the ColorPicker program –Provide three sliders that vary amount of RGB colors –Provide three quickset buttons to restore default RGB Graphical components needed –JFrame, JPanels, JSliders, JLabels, JButtons Transition diagram –Shows how specific components respond to events

Alice in Action with Java27 Example 2: Using Sliders and Buttons (continued)

Alice in Action with Java28 Example 2: Using Sliders and Buttons (continued)

Alice in Action with Java29 Example 2: Using Sliders and Buttons (continued)

Alice in Action with Java30 The ColorPicker Program Member inventory is provided below Instance variables –Eight handles to graphical components –Three integer variables for RGB colors –serialVersionUID ( long recommended by API) Constructor uses super() and the this notation Class member methods (up to line 42) –initializeFrame() –buildSliderPanel()

Alice in Action with Java31 The ColorPicker Program (continued) Class member methods (from line 43) –addRGBLabelsTo() –addSlidersTo() –addNumberLabelsTo() –buildColorPanel() –buildButtonPanel() private handler classes for RGB sliders –RedSliderListener –GreenSliderListener –BlueSliderListener

Alice in Action with Java32 The ColorPicker Program (continued) private handler classes for buttons –RedButtonListener –GreenButtonListener –BlueButtonListener Additional class member methods –setColor() –centerFrame() –main()

Alice in Action with Java33 The ColorPicker Program (continued)

Alice in Action with Java34 The ColorPicker Program (continued)

Alice in Action with Java35 The ColorPicker Program (continued)

Alice in Action with Java36 The ColorPicker Program (continued)

Alice in Action with Java37 The ColorPicker Program (continued)

Alice in Action with Java38 Building the ColorPicker GUI ColorPicker extends JFrame Instance variables –Two handles to JPanel s –Three handles to JSlider s –Three handles to JLabel s –Three int types for RGB values –One long type named serialVersionUID Constructor is organized around three major tasks –Initialize the instance variables –Build the GUI –Register listeners for the components

Alice in Action with Java39 Building the ColorPicker GUI (continued) Constructor calls super() and four helper methods initializeFrame() –First method called in the constructor –Initializes the JFrame –Passes BorderLayout manager to JPanel buildSliderPanel() –Second method called in the constructor –Builds a JPanel to store the RGB labels –Uses methods to add RGB labels, sliders, number labels –Adds slider panel in NORTH position of content pane

Alice in Action with Java40 Building the ColorPicker GUI (continued)

Alice in Action with Java41 Building the ColorPicker GUI (continued) buildColorPanel() –Third method called by the constructor –First line initializes myColorPanel as a new JPanel –The second line gives myColorPanel a border –Third line sends setPreferredSize() to color panel –Fourth line sets the color panel to its initial color –Fifth line adds the color panel to the content pane

Alice in Action with Java42 Building the ColorPicker GUI (continued) buildButtonPanel() –Fourth method called by the constructor –Defines JPanel using a GridLayout manager –Uses JButton class to build three buttons –Sets the foreground and background colors of buttons –Registers an ActionListener with each button –Adds each button to the button panel –Adds the finished button panel to the content pane

Alice in Action with Java43 Testing the GUI First test is designed to validate the GUI appearance –Comment out statements registering listeners User of program approves GUI’s appearance User requests to have JFrame centered – JFrame is centered after GUI has been constructed Overview of the centerFrame() method –Get the screen’s width and height dimensions –Evaluate the center (x, y) coordinates of the screen –Subtract GUI width from x and GUI height from y –Draw GUI at new (x, y ) point (upper-left corner of GUI)

Alice in Action with Java44 Testing the GUI (continued)

Alice in Action with Java45 Testing the GUI (continued)

Alice in Action with Java46 Building the ColorPicker Listeners JSlider produces a ChangeEvent ChangeEvent handler implements ChangeListener –Three handlers are needed for the three sliders ChangeListener declares stateChanged() –This method must be defined by each of the handlers Implementation logic of stateChanged() –Get the value of the slider –Update slider’s number label to reflect its changed value –Update the color panel to reflect the new color

Alice in Action with Java47 Building the ColorPicker Listeners (continued) JButton produces an ActionEvent ActionEvent handler implements ActionListener ActionListener –Three handlers are needed for the buttons ActionListener declares actionPerformed() –This method must be defined by each of the handlers Implementation logic of actionPerformed() –Invokes a utility method called setColor() –Pass three arguments (the RGB values) to setColor()

Alice in Action with Java48 Applets and the World Wide Web Elements of the Click-Clack-Cloe game –Two users play the game on a 3 x 3 grid –Click by player 1 turns a cell red –Click by player 2 turns a cell blue –Goal: set three adjacent cells to the same color Strategy for implementing the game in a program –Make each cell a button –Listener class will handle a button click event Change button color from white to appropriate color Check to see whether or not the click won the game

Alice in Action with Java49 Applets and the World Wide Web (continued)

Alice in Action with Java50 Applets vs. Applications Applet: Web-based program that runs in a browser Click-Clack-Cloe will be implemented as an applet Differences between applets and applications –An applet is defined as a subclass of JApplet –Most applets define GUIs and are event-driven –Applet uses init() in place of constructor and main() –Applets may only read files from their own Web site –An applet is embedded in a Web page –An applet is run in a Web browser or appletviewer

Alice in Action with Java51 Designing the Applet Furthering the design –Annotate the storyboard with graphical components –Build a transition diagram Instance variables needed –Handle for the feedback label –Handles for the nine cells –Variable to store the turn of the current player –Variable to store identification of the winner A listener should be registered to each of nine cells

Alice in Action with Java52 Designing the Applet (continued)

Alice in Action with Java53 Building the Applet Reminder: applet does not use constructor or main() Basic structure of ClickClackCloe –Instance variables –An init() method –Required listeners Instance variables used in ClickClackCloe –A handle to a two-dimensional JButton array –Integer constants to set the size of the JButton array –boolean types for Red’s turn and the game state –A handle to a JLabel

Alice in Action with Java54 Building the Applet (continued) The init () method –Line 18 passes BorderLayout to JPanel –Line 19 gives the content pane ( JPanel ) a border –Lines build JLabel and add it to content pane –Lines build grid panel and add it to content pane actionPerformed() method in ButtonListener –Identifies whether the event source was a JButton –If event source is a JButton, player turn is evaluated –Player turn controls how handleClick() is called handleClick() relies on gameOver() method

Alice in Action with Java55 Building the Applet (continued)

Alice in Action with Java56 Building the Applet (continued)

Alice in Action with Java57 Building the Applet (continued)

Alice in Action with Java58 Building the Applet (continued)

Alice in Action with Java59 Running the Applet Two choices: use a Web browser or appletviewer Applet must first be embedded in a Web page The appletviewer approach (in Eclipse) –Right-click anywhere in the applet’s editing area –Choose Run as -> Java Applet from the menu The appletviewer approach (without an IDE) –First build a Web page with a reference to the applet –Web page: text file containing HTML tags and data – tag includes three parameters: code (file location), width, and height

Alice in Action with Java60 Running the Applet (continued)

Alice in Action with Java61 Running the Applet (continued) The browser approach –Compile the applet –Build a Web page that references the applet –Open the Web page from within the browser World Wide Web: network based on Web servers Uniform resource locator (URL) –Specifies the address of a file on the Web How to publish an applet –Place folder with applet and Web page on Web server –Provide read access to the folder and its files

Alice in Action with Java62 Running the Applet (continued)