62
Alice in Action with Java Chapter 14 Events and GUIs

Alice in Action with Java

  • Upload
    tyra

  • View
    30

  • Download
    0

Embed Size (px)

DESCRIPTION

Alice in Action with Java. Chapter 14 Events and GUIs. 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 - PowerPoint PPT Presentation

Citation preview

Page 1: Alice in Action with Java

Alice in Action with Java

Chapter 14Events and GUIs

Page 2: Alice in Action with Java

Alice in Action with Java 2

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

Page 3: Alice in Action with Java

Alice in Action with Java 3

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

Page 4: Alice in Action with Java

Alice in Action with Java 4

Introduction: Miles to Kilometers and Vice Versa (continued)

Page 5: Alice in Action with Java

Alice in Action with Java 5

Introduction: Miles to Kilometers and Vice Versa (continued)

Page 6: Alice in Action with Java

Alice in Action with Java 6

Introduction: Miles to Kilometers and Vice Versa (continued)

Page 7: Alice in Action with Java

Alice in Action with Java 7

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)

Page 8: Alice in Action with Java

Alice in Action with Java 8

Introduction: Miles to Kilometers and Vice Versa (continued)

Page 9: Alice in Action with Java

Alice in Action with Java 9

Introduction: Miles to Kilometers and Vice Versa (continued)

Page 10: Alice in Action with Java

Alice in Action with Java 10

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

Page 11: Alice in Action with Java

Alice in Action with Java 11

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

Page 12: Alice in Action with Java

Alice in Action with Java 12

GUI Components

• javax.swing package: source of GUI components

Page 13: Alice in Action with Java

Alice in Action with Java 13

GUI Components (continued)

Page 14: Alice in Action with Java

Alice in Action with Java 14

GUI Components (continued)

Page 15: Alice in Action with Java

Alice in Action with Java 15

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

Page 16: Alice in Action with Java

Alice in Action with Java 16

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

Page 17: Alice in Action with Java

Alice in Action with Java 17

GUI Components (continued)

Page 18: Alice in Action with Java

Alice in Action with Java 18

GUI Components (continued)

Page 19: Alice in Action with Java

Alice in Action with Java 19

GUI Components (continued)

Page 20: Alice in Action with Java

Alice in Action with Java 20

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

Page 21: Alice in Action with Java

Alice in Action with Java 21

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

Page 22: Alice in Action with Java

Alice in Action with Java 22

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

Page 23: Alice in Action with Java

Alice in Action with Java 23

Events (continued)

Page 24: Alice in Action with Java

Alice in Action with Java 24

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

Page 25: Alice in Action with Java

Alice in Action with Java 25

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

Page 26: Alice in Action with Java

Alice in Action with Java 26

Example 2: Using Sliders and Buttons

• RGB color– Consists of different amounts of red, green, and blue– Range of color values: 0 - 255

• 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

Page 27: Alice in Action with Java

Alice in Action with Java 27

Example 2: Using Sliders and Buttons (continued)

Page 28: Alice in Action with Java

Alice in Action with Java 28

Example 2: Using Sliders and Buttons (continued)

Page 29: Alice in Action with Java

Alice in Action with Java 29

Example 2: Using Sliders and Buttons (continued)

Page 30: Alice in Action with Java

Alice in Action with Java 30

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

Page 31: Alice in Action with Java

Alice in Action with Java 31

The ColorPicker Program (continued)

• Class member methods (from line 43)– addRGBLabelsTo()– addSlidersTo()– addNumberLabelsTo()– buildColorPanel()– buildButtonPanel()

• private handler classes for RGB sliders– RedSliderListener– GreenSliderListener– BlueSliderListener

Page 32: Alice in Action with Java

Alice in Action with Java 32

The ColorPicker Program (continued)

• private handler classes for buttons– RedButtonListener– GreenButtonListener– BlueButtonListener

• Additional class member methods– setColor()– centerFrame()– main()

Page 33: Alice in Action with Java

Alice in Action with Java 33

The ColorPicker Program (continued)

Page 34: Alice in Action with Java

Alice in Action with Java 34

The ColorPicker Program (continued)

Page 35: Alice in Action with Java

Alice in Action with Java 35

The ColorPicker Program (continued)

Page 36: Alice in Action with Java

Alice in Action with Java 36

The ColorPicker Program (continued)

Page 37: Alice in Action with Java

Alice in Action with Java 37

The ColorPicker Program (continued)

Page 38: Alice in Action with Java

Alice in Action with Java 38

Building the ColorPicker GUI

• ColorPicker extends JFrame• Instance variables

– Two handles to JPanels– Three handles to JSliders– Three handles to JLabels– 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

Page 39: Alice in Action with Java

Alice in Action with Java 39

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

Page 40: Alice in Action with Java

Alice in Action with Java 40

Building the ColorPicker GUI (continued)

Page 41: Alice in Action with Java

Alice in Action with Java 41

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

Page 42: Alice in Action with Java

Alice in Action with Java 42

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

Page 43: Alice in Action with Java

Alice in Action with Java 43

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)

Page 44: Alice in Action with Java

Alice in Action with Java 44

Testing the GUI (continued)

Page 45: Alice in Action with Java

Alice in Action with Java 45

Testing the GUI (continued)

Page 46: Alice in Action with Java

Alice in Action with Java 46

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

Page 47: Alice in Action with Java

Alice in Action with Java 47

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

Page 48: Alice in Action with Java

Alice in Action with Java 48

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

Page 49: Alice in Action with Java

Alice in Action with Java 49

Applets and the World Wide Web (continued)

Page 50: Alice in Action with Java

Alice in Action with Java 50

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

Page 51: Alice in Action with Java

Alice in Action with Java 51

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

Page 52: Alice in Action with Java

Alice in Action with Java 52

Designing the Applet (continued)

Page 53: Alice in Action with Java

Alice in Action with Java 53

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

Page 54: Alice in Action with Java

Alice in Action with Java 54

Building the Applet (continued)

• The init() method– Line 18 passes BorderLayout to JPanel – Line 19 gives the content pane (JPanel) a border– Lines 20-24 build JLabel and add it to content pane– Lines 25-38 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

Page 55: Alice in Action with Java

Alice in Action with Java 55

Building the Applet (continued)

Page 56: Alice in Action with Java

Alice in Action with Java 56

Building the Applet (continued)

Page 57: Alice in Action with Java

Alice in Action with Java 57

Building the Applet (continued)

Page 58: Alice in Action with Java

Alice in Action with Java 58

Building the Applet (continued)

Page 59: Alice in Action with Java

Alice in Action with Java 59

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– <applet> tag includes three parameters:

• code (file location), width, and height

Page 60: Alice in Action with Java

Alice in Action with Java 60

Running the Applet (continued)

Page 61: Alice in Action with Java

Alice in Action with Java 61

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

Page 62: Alice in Action with Java

Alice in Action with Java 62

Running the Applet (continued)