1 / 62

Alice in Action with Java

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

tyra
Download Presentation

Alice in Action with Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Alice in Action with Java Chapter 14 Events and GUIs

  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 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 Alice in Action with Java

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

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

  6. Introduction: Miles to Kilometers and Vice Versa (continued) 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 • KmsListenerandMilesListener • Contain methods to handle event (provide conversion) Alice in Action with Java

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

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

  10. Java GUI Components, Events, and Listeners • Four parts to MilesKmsConverter • MilesKmsConverterconstructor • Lines 9-27: constructs the GUI • MilesListenerclass • Lines 29-43: handles user events in the “Miles:” box • KmsListenerclass • 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 Java

  11. The main()Method • First line: call to MilesKmsConverterconstructor • Builds a MilesKmsConverterobject • 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 Java

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

  13. GUI Components (continued) Alice in Action with Java

  14. GUI Components (continued) Alice in Action with Java

  15. GUI Components (continued) • javax.swing package: source of GUI components • The JFrameclass • Window including standard features such as title bar • Application using a GUI will first extend JFrame • MilesKmsConverteris a JFrame • Use super()to invoke one of the JFrame constructors • Example: super("Miles-Kms"); • The JPanelclass • Corresponds to a window pane • A layout manager can be passed to one constructor 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 JLabelcomponent • Used to provide a label Alice in Action with Java

  17. GUI Components (continued) Alice in Action with Java

  18. GUI Components (continued) Alice in Action with Java

  19. GUI Components (continued) Alice in Action with Java

  20. GUI Components (continued) • The JTextFieldcomponent • 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 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 • ActionEventis 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 Java

  22. Events • Some GUI components can generate events • Example: ActionEvent is generated in JTextField • Different events are handled by different listeners • Example: KeyEventis 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 Java

  23. Events (continued) 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, ifstatement selects response • Disadvantage: leads to complex, error prone methods • Write specialized listener for each component Alice in Action with Java

  25. The serialVersionUIDAttribute • 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 longtype 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 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 Alice in Action with Java

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

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

  29. Example 2: Using Sliders and Buttons (continued) 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 (longrecommended by API) • Constructor uses super()and the this notation • Class member methods (up to line 42) • initializeFrame() • buildSliderPanel() 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 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() Alice in Action with Java

  33. The ColorPicker Program (continued) Alice in Action with Java

  34. The ColorPicker Program (continued) Alice in Action with Java

  35. The ColorPicker Program (continued) Alice in Action with Java

  36. The ColorPicker Program (continued) Alice in Action with Java

  37. The ColorPicker Program (continued) Alice in Action with Java

  38. Building the ColorPicker GUI • ColorPickerextendsJFrame • Instance variables • Two handles to JPanels • Three handles to JSliders • Three handles to JLabels • Three int types for RGB values • One longtype 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 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 JPanelto 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 Java

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

  41. Building the ColorPicker GUI (continued) • buildColorPanel() • Third method called by the constructor • First line initializes myColorPanelas a new JPanel • The second line gives myColorPanela 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 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 ActionListenerwith each button • Adds each button to the button panel • Adds the finished button panel to the content pane 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 • JFrameis 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 Java

  44. Testing the GUI (continued) Alice in Action with Java

  45. Testing the GUI (continued) Alice in Action with Java

  46. Building the ColorPickerListeners • JSlider produces a ChangeEvent • ChangeEventhandler implements ChangeListener • Three handlers are needed for the three sliders • ChangeListenerdeclares 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 Java

  47. Building the ColorPickerListeners (continued) • JButton produces an ActionEvent • ActionEventhandler implements ActionListener • ActionListener • Three handlers are needed for the buttons • ActionListenerdeclares 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 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 Alice in Action with Java

  49. Applets and the World Wide Web (continued) 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 Alice in Action with Java

More Related