Presentation is loading. Please wait.

Presentation is loading. Please wait.

Alice in Action with Java Chapter 14 Events and GUIs.

Similar presentations


Presentation on theme: "Alice in Action with Java Chapter 14 Events and GUIs."— Presentation transcript:

1 Alice in Action with Java Chapter 14 Events and GUIs

2 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

3 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

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

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

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

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

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

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

10 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

11 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

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

13 Alice in Action with Java13 GUI Components (continued)

14 Alice in Action with Java14 GUI Components (continued)

15 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

16 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

17 Alice in Action with Java17 GUI Components (continued)

18 Alice in Action with Java18 GUI Components (continued)

19 Alice in Action with Java19 GUI Components (continued)

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

21 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

22 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

23 Alice in Action with Java23 Events (continued)

24 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

25 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

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

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

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

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

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

31 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

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

33 Alice in Action with Java33 The ColorPicker Program (continued)

34 Alice in Action with Java34 The ColorPicker Program (continued)

35 Alice in Action with Java35 The ColorPicker Program (continued)

36 Alice in Action with Java36 The ColorPicker Program (continued)

37 Alice in Action with Java37 The ColorPicker Program (continued)

38 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

39 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

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

41 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

42 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

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

44 Alice in Action with Java44 Testing the GUI (continued)

45 Alice in Action with Java45 Testing the GUI (continued)

46 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

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

48 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

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

50 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

51 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

52 Alice in Action with Java52 Designing the Applet (continued)

53 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

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

55 Alice in Action with Java55 Building the Applet (continued)

56 Alice in Action with Java56 Building the Applet (continued)

57 Alice in Action with Java57 Building the Applet (continued)

58 Alice in Action with Java58 Building the Applet (continued)

59 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

60 Alice in Action with Java60 Running the Applet (continued)

61 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

62 Alice in Action with Java62 Running the Applet (continued)


Download ppt "Alice in Action with Java Chapter 14 Events and GUIs."

Similar presentations


Ads by Google