Go Over Test - PowerPoint PPT Presentation

1 / 43
About This Presentation
Title:

Go Over Test

Description:

... to the text field. May need to determine which text field caused the event ... If a class should recognize mouse events, the class must implement one or both ... – PowerPoint PPT presentation

Number of Views:22
Avg rating:3.0/5.0
Slides: 44
Provided by: davidh67
Category:
Tags: over | test

less

Transcript and Presenter's Notes

Title: Go Over Test


1
Go Over Test 2
  • Grade Breakdown Fall 2005
  • A's 3
  • B's 3
  • C's 2
  • D's 2
  • How to Study for CSc-037
  • Visit the instructor's office for help
  • Work on HW Early (as opposed to starting it the
    night before it is due)
  • Read Text Before After Class
  • Make sure you understand what's happening in Lab
  • Play with Sample Programs in Course Folder
  • Work on Exercises in Textbook
  • Try Sample Tests without looking at answers
  • (not just the night before the test)

2
Week 08 - a
  • Swing GUIJTextField, JTextArea, JButtonJLabel,
    JPanel, JFrame
  • EventsActionListener InterfaceMouseListener,
    MouseMotionListener

3
Sample Programs Referenced(code located in
course folder)
  • GUI Hello
  • Temperature Convert
  • Turtle Graphics
  • Measles (ClickMe)
  • TicTacToe
  • Sleepy Eyes
  • java events.EventLab

4
AWT and Swing
  • GUI Graphical User Interface
  • Windows, buttons, text boxes, etc.
  • AWT Abstract Window Toolkit
  • Early set of classes for building GUIs
  • Platform dependent
  • Swing
  • More recent set of classes for building GUIs
  • Platform independent
  • Relies on AWT

5
Categories of Classes
  • Components
  • like frames, panels, buttons, text boxes,
  • Layout management
  • Control flow of components
  • Help position components
  • Events
  • Generated when users click buttons, move the
    mouse,
  • Listeners
  • Methods activated by operating system when events
    occur

6
Creating a GUIHello
  • Start with a class that IS A JFrame
  • public class HelloGUI extends JFrame
  • Set its size, title, and other properties
  • setSize(width, height)
  • setTitle(text)
  • setResizeable(false) // optional
  • Set what it should do when the user closes it
  • setDefaultCloseOperation( EXIT_ON_CLOSE)
  • (Precludes need for WindowListener)
  • Needed in JFrame, not Applet
  • Write an application class that instantiates the
    GUI and makes it visible
  • theGUI.setVisible(true)

7
Example Problem
175 pixels
375 pixels
8
Frames
  • A frame is a window with a title bar and a border
  • The Frame class is a subclass of Container class
  • Container class objects may have other components
    (e.g. Buttons or Labels) added to them using the
    add method
  • A typical Java GUI will create and display one or
    more frames
  • To make a frame visible the message
    setVisible(true) must be sent to the frame

9
JFrame and Content Pane
10
Create the JFrame
  • The HelloGUI class
  • Extends JFrame
  • Constructor that
  • Sets the size to 375 by 175
  • Sets the title to Hello
  • Makes the frame not resizable
  • Sets the close operation
  • Application class that
  • Instantiates a HelloGUI object
  • Makes the GUI visible

11
Add Instructions
  • Need Container object to hold the content pane
  • Set its background color to white
  • Set the layout to null (more on layouts later)
  • Need a JLabel object for the instructions
  • Set the bounds
  • Position at (125, 10)
  • Dimensions 250 by 25
  • Add the JLabel object to the content pane

12
Add Text Boxes and Buttons
  • Make instance variables for the two text boxes
    and buttons
  • JTextField and JButton
  • Instantiate in GUI constructor
  • Set bounds
  • Name (125, 40, 200, 25)
  • Message (125, 100, 200, 25)
  • Enter (125, 70, 125, 25)
  • Clear (250, 70, 75, 25)
  • Add text boxes and buttons to content pane

13
Java Event Model
  • An event model describes how events are handled
    in the language
  • Java uses event generators and event listeners
  • An event generator initiates an event of a
    particular type
  • e.g. clicking a button generates an action event
  • A event listener listens for and responds to
    events of a particular type
  • e.g. our GUI will listen for action events and
    have a method that will say what to do in
    response to an action event
  • Also, the java.awt.event package must be imported

14
Registering as anEvent Listener
  • The GUI needs to tell the event generator that it
    is a listener
  • This is called registering
  • An event listener registers itself with an event
    generator
  • e.g. enter.addActionListener(this)
  • enter is the event generator
  • this (the GUI) is the listener
  • In order to for an object to be a listener it
    must follow protocols
  • It must have an actionPerformed event
  • The protocols are defined in the ActionListener
    interface
  • The listener class must implement ActionListener

15
The actionPerformed Method
  • Specified in the ActionListener interface
  • public void actionPerformed(ActionEvent e)
  • Does the task(s) that should be performed when
    the action occurs
  • E.g. Writes the message in the text box
  • Not explicitly called
  • Automatically called when an event occurs for
    which there is a registered listener
  • The parameter gives the action object that is
    being processed
  • That way we can tell which button was pressed

16
Working with Images
  • An object of the JLabel class can hold text or an
    ImageIcon object
  • An ImageIcon object holds an image
  • new ImageIcon( filename of image )
  • Modify the GUI
  • Add another JLabel object as an instance variable
  • Instantiate it with a constructor that takes an
    ImageIcon object as its argument
  • e.g. image new JLabel(new ImageIcon(RedFace.gif
    )
  • Set its bounds to (15, 20, 90, 99)
  • Add it to the content pane
  • Move the image RedFace and BlueFace into the
    project folder

17
Changing the Images
  • Modify the actionPerformed method to change the
    image
  • Set the image to the red face when the enter
    button is pressed
  • Set the image to the blue face when the clear
    button is pressed.
  • Use setIcon method of the JLabel
  • e.g. Image.setIcon(new ImageIcon(BlueFace.gif)

18
Display the MessageHello
  • Modify the GUI to implement ActionListener
  • Register the GUI as a listener for both buttons
  • enter.addActionListener(this)
  • clear.addActionListener(this)
  • Write an actionPerformed method to set the text
    in message to the String "Hello, " plus the text
    in name.
  • Use the setText and getText methods of the
    JTextFields
  • Try it
  • Try the enter button
  • Try the clear button
  • How do we make them do different things?

19
Sensing the Object
  • Need to know who initiated the event
  • The ActionEvent object that is the methods
    parameter holds the information
  • Its getSource() method can be called to get a
    reference to the object
  • e.g. e.getSource() would return a reference to
    either the enter or clear button object
  • We can test it and use a decision structure to
    decide what to do
  • Add
  • Object buttonPressed e.getSource()
  • The decision structure

20
Entering Text can alsoTrigger an actionEvent
  • Add the actionListener to the text field
  • May need to determine which text field caused the
    event
  • See Temperature Project in BlueJ
  • (also listed on next 3 slides)
  • Watch what happens if we resize the window
  • Flow Layout
  • Don't need to specify the location of each object

21
Temperature Conversion(1 of 3)
  • import java.awt.
  • import java.awt.event.
  • import javax.swing.
  • /
  • GUI to convert between Fahrenheit and
    Centigrade Temperatures.
  • _at_author Dave Hannay
  • _at_version 21 February 2004
  • /
  • public class Temperature extends JFrame
    implements ActionListener
  • JTextField txtFahr new JTextField(6),
  • txtCent new JTextField(6)

22
Temperature Conversion(2 of 3)
  • public Temperature()
  • this.setSize(250,100)
  • this.setTitle("Temperature Conversion")
  • this.setDefaultCloseOperation(EXIT_ON_CLOSE)
  • Container frame this.getContentPane()
  • frame.setLayout(new FlowLayout())
  • Panel fahrPanel new Panel()
  • Panel centPanel new Panel()
  • fahrPanel.add(new JLabel("Fahrenheit"))
    fahrPanel.add(txtFahr)
  • centPanel.add(new JLabel("Centigrade"))
    centPanel.add(txtCent)
  • frame.add(fahrPanel)
  • frame.add(centPanel)
  • txtFahr.addActionListener(this)
  • txtCent.addActionListener(this)
  • // end of Temperature constructor

23
Temperature Conversion(3 of 3)
  • public void actionPerformed(ActionEvent e)
  • double fahr, cent
  • // check for user input in txtFahr TextField
  • if (e.getSource() txtFahr)
  • fahr Double.parseDouble(txtFahr.getText())
  • cent 5.0 (fahr - 32.0) / 9.0
  • txtCent.setText(""cent) // the old
    convert to String trick
  • // end of fahrenheit to centigrade
  • else
  • cent Double.parseDouble(txtCent.getText())
  • fahr 9.0 cent / 5.0 32.0
  • txtFahr.setText(""fahr)
  • // end of centigrade to fahrenheit
  • // end of actionPerformed method
  • // end of Temperature class

24
HW 7(see Sample HW 7)
  • GUI Interface for CD Collection
  • See Textbook, problem 4, page 514
  • Store info on your CD Collection in an array (or
    Vector if you prefer) of Objects of type CD
  • Do not use Text Files for this assignment
  • i.e. do not look ahead to chapter 8
  • It will tend to make things more confusing

25
Java BREAK
26
Turtle Graphics
  • Moves around screen based on button clicks
  • Vector to remember where it has been
  • so it can draw trailing line
  • See in BlueJ

27
Mouse Interfaces
  • Java AWT provides a several interfaces for
    handling mouse events
  • MouseListener
  • has abstract methods mouseClicked, mousePressed,
    mouseReleased, mouseEntered, mouseExited
  • MouseMotionListener
  • has abstract methods mouseMoved, mouseDragged
  • If a class should recognize mouse events, the
    class must implement one or both of the
    interfaces
  • The class must then contain concrete definitions
    of ALL of the methods in the interface(s)
  • if a method is not used, its body may be empty

28
Creating "Mouse Click" Listeners
  • Import the java.awt.event package
  • In the class header, add the words implements
    MouseListener
  • Send the addMouseListerner(this) message to the
    mouse event manager (should be done in the
    constructor method)
  • Define methods mouseClicked, mousePressed,
    mouseReleased, mouseEntered, mouseExited

29
Mouse Listener Template
  • import java.awt.event.
  • public class classname implements MouseListener
  • // include manager.addMouseListener(this)
  • // manager is a an applet for now, so omitted
  • // in some initialization method
  • public void mouseClicked (MouseEvent e)
  • public void mousePressed (MouseEvent e)
  • public void mouseReleased (MouseEvent e)
  • public void mouseEntereded (MouseEvent e)
  • public void mouseExited (MouseEvent e)

30
Finding Mouse Location
  • Inside mouseClicked, the argument e of type
    MouseEvent can be used to find the location of
    the mouse cursor
  • The call e.getX( ) returns the value of the
    horizontal coordinate of the mouse cursor
    position
  • The call e.getY( ) returns the value of the
    vertical coordinate of the mouse cursor position

31
MouseListener ExampleMeasles (ClickMe)
  • import java.awt.event.
  • implements MouseListener clause in method header
  • addMouseListener(this) in init method
  • Every MouseListener method must be implemented,
    even if empty
  • 5 of them
  • Use of getX(), getY()

32
ClickMe ClassRun in BlueJ
  • import java.awt.
  • import java.applet.
  • import java.awt.event.
  • import java.util.
  • // David Hannay 21 February 2004
  • public class ClickMe extends Applet implements
    MouseListener
  • private int radius 7
  • private Color color Color.RED
  • private Vector spots
  • public void init()
  • spots new Vector()
  • addMouseListener(this)
  • // end of init method
  • public void paint(Graphics g)
  • for (int s0 sltspots.size() s)
  • int x ((Point) spots.get(s)).x
  • int y ((Point) spots.get(s)).y
  • g.setColor(color)

33
ClickMeHandling Mouse Actions
  • public void mouseClicked(MouseEvent event)
  • spots.addElement(new Point(event.getX(),
    event.getY()))
  • repaint()
  • // end of mouseClicked method
  • public void mousePressed(MouseEvent event)
  • public void mouseReleased(MouseEvent event)
  • public void mouseExited(MouseEvent event)
  • color Color.GREEN
  • repaint()
  • // end of mouseExited method
  • public void mouseEntered(MouseEvent event)
  • color Color.RED
  • repaint()
  • // end of mouseEntered method
  • // end of ClickMe class

34
TicTacToe
  • A more "practical" use of MouseListener
  • Run Program in BlueJ, then take a look at the
    TicTacToe class

35
TTTBoard Class (1 of 2)
  • public class TTTBoard
  • public static int EX 0, OH 1, VACANT 2
  • private int sq VACANT, VACANT, VACANT,
  • VACANT, VACANT, VACANT,
  • VACANT, VACANT,
    VACANT
  • public boolean isMarked (int row, int col)
  • return sqrow-1col-1 ! VACANT
  • // end of isMarked method
  • public int getMark (int row, int col)
  • return sqrow-1col-1
  • // end of getMark method
  • public void putO (int row, int col)
  • sqrow-1col-1 OH
  • // end of putO method
  • public void putX (int row, int col)

36
TTTBoard Class (2 of 2)
  • public boolean done ()
  • for (int i0 ilt3 i)
  • for (int j0 jlt3 j)
  • if (sqijVACANT) return false
  • return true
  • // end of done method
  • public int winner ()
  • int center, ul, lr
  • center sq11
  • if ((center sq00 center
    sq22)
  • (center sq02 center
    sq20)
  • (center sq01 center
    sq21)
  • (center sq10 center
    sq12)) return center
  • ul sq00
  • if ((ul sq01 ul sq02)
  • (ul sq10 ul sq20))
    return ul
  • lr sq22
  • if ((lr sq12 lr sq02)

37
Creating Mouse Motion Listeners
  • Import the java.awt.event package
  • In the class header, add the words implements
    MouseMotionListener
  • Send the message addMouseMotionListener(this) to
    the mouse event manager (should be done in the
    constructor method)
  • Define methods mouseMoved (mouse up) and
    mouseDragged (mouse down)

38
Mouse Motion Listener Template
  • import java.awt.event.
  • public class classname implements
    MouseMotionListener
  • // include manager.addMouseListener(this)
  • // (manager. not needed for applets)
  • // in some initialization method
  • public void mouseMoved (MouseEvent e)
  • public void mouseDragged (MouseEvent e)

39
Mouse Motion
  • mouseMoved will be called each time the mouse
    makes a significantly large movement
  • mouseDragged will be called instead if the mouse
    button is pressed and the mouse makes a
    significantly large movement

40
Listening to All Mouse Events
  • To catch all seven mouse events use the following
    class header
  • public class classname implements MouseListener,
    MouseMotionListener
  • You then need to define all seven mouse methods
    mouseMoved, mouseDragged, mouseClicked,
    mousePressed, mouseReleased, mouseEntered,
    mouseExited

41
SleepyEyes
  • See in BlueJ
  • implements MouseListener and MouseMotionListener
  • several concrete methods are implemented
  • others are empty
  • do nothing

42
EventLab(AnimatedIllustrations)
  • Everyone grab a PC and double-click MS-DOS prompt
    icon
  • "Volunteer" to run it on instructor's console
  • java events.EventLab

43
Java BREAK
Write a Comment
User Comments (0)
About PowerShow.com