Event-Driven Programming - PowerPoint PPT Presentation

1 / 44
About This Presentation
Title:

Event-Driven Programming

Description:

Chapter 7. Java: an Introduction to Computer ... Often the parent for windows (descendents of Frame class) ... All three are descendents of the class Container ... – PowerPoint PPT presentation

Number of Views:20
Avg rating:3.0/5.0
Slides: 45
Provided by: lew119
Category:

less

Transcript and Presenter's Notes

Title: Event-Driven Programming


1
Chapter 7
Event-Driven Programming Using the AWT
  • Event-Driven Programming
  • GUIs and the AWT
  • Simple Window Interfaces
  • Components, Containers, and Layout Managers
  • Panels and Text Components
  • Adding Menus
  • Inner Classes

2
Event-Driven Programming
  • A different approach to program design
  • Programs react to events, e.g.
  • mouse click
  • key press
  • menu selection
  • button selection
  • message sent from printer
  • etc.
  • GUI graphical user interface
  • windows, scroll bars, menus, radio buttons, etc.
  • a special case of event-driven programming
  • the only type of event we will be concerned with
    in this chapter
  • An event is an object

3
AWT
  • Abstract Window Toolkit
  • Implements GUI
  • A standard part of Java
  • Not fancy, but adequate
  • Makes extensive use of inheritance
  • Based on events and event handlers
  • Firing an event when an object generates an
    event
  • Listener object
  • every object that can fire an event, such as a
    button, can have one or more listener objects
  • Listener objects have methods (called event
    handlers) that perform actions depending on the
    event
  • You the programmer write these event handlers

4
WARNING!
  • Programs that use the AWT can hang the computer
  • Save your work before running
  • a program using the AWT!

5
Example include the AWT library extend Frame
  • The 1st two lines are needed when you use the AWT
    library
  • 3rd line starts the class definition
  • FirstWindow is derived from AWT Frame class
  • Frame is derived from the more basic class AWT
    Window class
  • Frame has a window, border, title bar, and close
    button
  • Frame will be modified by adding properties to
    meet the program requirements

The first few lines of FirstWindow (Display
7.1/page 329)
5
Chapter 6
Java an Introduction to Computer Science
Programming - Walter Savitch
6
A word about displays pixels
(0, 0)
  • Displays are organized as a 2-dimensional grid of
    pixels
  • pixel picture element
  • the smallest "addressable" unit of a screen
  • "Address" coordinates
  • (width, height)
  • The origin has coordinates (0,0) and is in upper
    left
  • increasing width is to right
  • increasing height is down

Increasing width (x direction)
(75, 100)
Increasing height (y direction)
7
Example define paint method Graphics class and
drawString
Additional method paint (Display 7.1/page 329)
  • FirstWindow inherits properties of Frame and adds
    paint method
  • paint is called by AWT, not by FirstWindow
  • One argument, g, of type Graphics, is passed
  • think of it as a portion of the screen in which
    the object is to be painted
  • Every Graphics object has a drawString method
  • 75 and 100 are the coordinates of the start of
    the window
  • they depend on the programming environment
  • you may have to adjust the numbers
  • some things are done by trial and error try it
    and see

7
Chapter 6
Java an Introduction to Computer Science
Programming - Walter Savitch
8
Exampledefine system constants
Conventional style of declaring systemconstants
(Display 7.1/page 329)
  • The window width and height are system constants
    that specify the window size in pixels
  • may adjust for different systems
  • public allows other classes to read the values
  • static final prevents any other class from
    changing the values
  • Using variables instead of "hard coded" numbers
    simplifies maintenance
  • just change these two lines and recompile to
    change the window size
  • avoids looking through the entire file for every
    occurrence of the numbers

8
Chapter 6
Java an Introduction to Computer Science
Programming - Walter Savitch
9
Example display windowdefine and register
listeners
  • 1) setSize a Frame method to set the size of the
    window
  • 2) listener an object of the windowDestroyer
    class
  • an object that receives events from an object
  • should close window if "close window" button is
    clicked
  • must be defined (written)
  • 3) Registering the listener
  • associates the listener object with an
    event-firing object
  • the listener will listen for events fired by the
    associated object
  • 4) setVisible a Frame method to make the window
    visible

The main method (Display 7.1/page 329)
9
Chapter 6
Java an Introduction to Computer Science
Programming - Walter Savitch
10
Example windowAdapter abstract class and
System.exit
  • windowAdapter
  • Often the parent for windows (descendents of
    Frame class)
  • an abstract class it has methods but they are
    undefined, so you need to define whichever
    methods you will use
  • See Display 7.3/page 334 for windowAdapter
    methods
  • "close window" in the only event in this case
  • so windowClosing method must be defined
  • System.exit(0) ends the Java program
  • "0" is the conventional value used to indicate
    normal termination

windowDestroyer definition (Display 7.2/page 332)
10
Chapter 6
Java an Introduction to Computer Science
Programming - Walter Savitch
11
Useful methods in Frame class
  • setTitle inserts a string in the title bar of the
    window
  • setBackground(Color.blue) specifies the
    background color of the window
  • Display 7.6/page 343 lists other predefined color
    values
  • addWindowListener registers a listener for events
  • setSize and paint have already been described
  • etc. - see Display 7.7/page 344

12
Two principle ways tocreate new classes from old
ones
  • One method Inheritance
  • Use extend to create a custom window based on an
    existing class
  • For example
  • FirstWindow extends Frame
  • Another Container class
  • Use a container class
  • Use the add method to place items in it
  • Items placed in a container class are called
    components
  • Three kinds of objects to deal with
  • 1. The container class itself (usually a window)
  • 2. The components to add to it
  • 3. The layout manager

13
AWT container class
  • AWT container classes Window, Panel, Frame
  • All three are descendents of the class Container
  • Custom windows are built by adding components to
    a container class, usually in the constructor
  • Use the add method inherited from Container to
    place items in the new (container) class
  • Components items added to a container
  • for windows buttons, menus, text fields, etc.
  • Component is also a class
  • The AWT class hierarchy with Container and
    Component classes is shown on the next slide
    (Display 7.9/page 350)

14
Hierarchy of AWT classes
Object
Display 7.9/page 350
MenuComponent
Component
AWT
MenuItem
Container
Button
Menubar
Label
Menu
Window
TextComponent
Panel
Frame
TextArea
TextField
Key
Class
If there is a line between two classes, then the
lower class is a derived class of the higher
class. Not all AWT components are shown.
Abstract Class
15
Example creating a window using a container
class and components
ButtonDemo constructor
  • ButtonDemo(Display 7.8/page 347)
  • The constructor is shown in box at right
  • Note the code to create and add buttons (shown in
    blue)

16
ExampledrawString and repaint
Using a String instance variable in drawString
  • The String instance variable theText is used as
    an argument in drawString so the text inside the
    window can be changed easily
  • actionPerformed method determines which event
    occurred (which button was clicked) and changes
    the value of theText accordingly
  • repaint()is called to update the window with the
    new value of theText

17
Example action listeners
  • Different kinds of components require different
    kinds of listeners
  • Buttons fire events of type ActionEvent which
    require action listeners
  • ActionListener is not a class, it is a property
    (or interface) of a class
  • To give the ActionListener property to a class
  • 1. Add implements ActionListener to the
    beginning of the class definition, e.g.
  • public class ButtonDemo extends Frame implements
    ActionListener
  • ltstatements to define classgt
  • 2. Define a method named actionPerformed
  • Use addActionListener to add an action listener
    for a button, e.g.
  • Button stopButton new Button("Red")
  • stopButton.addActionListener(this)
  • See definition of ButtonDemo, Display 7.8/page
    347

18
actionPerformed method
actionPerformed method for ButtonDemo
  • Usually a selection (branching) statement that
    determines which action event fired and performs
    the appropriate action
  • getActionCommand reads the text value assigned to
    the whichever button was clicked
  • the text value was assigned when the Button
    object was created

19
Layout managers
  • Three basic layout managers provided with AWT1.
    FlowLayout2. BorderLayout3. GridLayout
  • There are others but they are not covered in this
    text

20
FlowLayout
  • To create a FlowLayout objectsetLayout(new
    FlowLayout())
  • Arranges components in the order they are added
  • starting in upper left of window (or other
    object) and proceeding to the right
  • when the top line is full it goes to the next
    line, etc.
  • Example ButtonDemo (Display 7.8/page 347) uses a
    flow layout

21
BorderLayout
  • To create a BorderLayout objectsetLayout(new
    BorderLayout())
  • Components can be placed in any one of five
    regions
  • "North"
  • "South"
  • "East"
  • "West"
  • "Center"

22
Example BorderLayout
  • In the constructor for some container
    objectsetLayout(new BorderLayout())add(new
    Button("Up"),"North")add(new Button("Down"),"Sou
    th")add(new Button("Right"),"East")add(new
    Button("Left"),"West")add(new Button("Straight
    ahead"),"Center")

The result
Up
Left
Right
Straight ahead
Down
23
GridLayout
  • Arranges components in a two-dimensional grid
    (rows and columns)
  • Each entry is the same size
  • For a grid with two rows and three
    columnssetLayout(new GridLayout(2,3))
  • the first argument is the number of rows
  • the second argument is the number of columns
  • creates a layout like this

24
Summary for creating simple window interface
  • 1. Derive a window object from Frame and add
    components.
  • 2. You must register a window listener for the
    close-window button
  • e.g., by adding the following to the GUI class
    definition within a constructor
    addWindowListener(new WindowDestroyer())
  • See Display 7.2/page 332 for a definition of
    WindowDestroyer.
  • 3. Some components, e.g. buttons, generate
    action events, so the GUI (or some other class)
    must be made an action listener.
  • Every component that generates an action event
    should have an action listener registered with
    it.
  • Use addActionListener to register an action
    listener.
  • 4. Use implements ActionListener at the
    beginning of the class definition to make your
    GUI (or other class) an action listener.
  • You also need to add a definition of the method
    actionPerformed to the class.
  • 5. There are other ways, but this one is simple
    and commonly used.

25
Programming tips
  • 1. Don't reinvent the wheel copy a similar
    program and modify it.
  • Obviously there is a lot of detail to deal with,
    so start with a program similar to what you need
    - the sample programs in each chapter are often
    good starting points for doing the Programming
    Exercises at the end of the chapter.
  • However, it is NOT ok to copy another student's
    work!
  • 2. See Display 7.11/page 360 for an outline of
    the code to create a simple GUI class. You may
    want to create this file and use it as a
    template copy it and modify the copy to create a
    new GUI.

26
WindowListener options
  • 1. Make the window itself the button listener by
    implementing the ActionListener interface
  • we did this when we placed buttons in a window
  • 2. Make the window listener a separate class
  • we did this for the window-closing button by
    defining WindowDestroyer
  • 3. Make the window itself the window listener by
    implementing the WindowListener interface

27
More about interfaces
  • Interfaces are just a collection of undefined
    methods
  • A Java class can be derived from only one base
    class but can implement more than one interface
  • All methods in an interface must be defined
  • unused methods can be defined with empty bodies,
    e.g.public void windowDeiconified(WindowEvent
    e)
  • ActionListener has only one method
    (ActionPerformed), but WindowListener has seven
    methods
  • if you do not need the other methods, using
    ActionListener instead of WindowListener avoids
    having to write the empty method definitions

28
The Panel class
  • A container class to group objects
  • Used to subdivide a Frame into different areas
  • For example, if you want two buttons in the south
    area of a border layout, put the two objects in a
    panel and place the panel in the south position
  • Typical program organization
  • Create new panel
  • set panel attributes, e.g. background color and
    panel layout
  • create and add objects such as buttons
  • Establish the overall layout and place the panel
    in the layout
  • Example code Display 7.13/page 366

29
Example Panel
PanelDemo constructor from Display 7.13/page 366
create panel
place panel in GUI
29
Chapter 7
Java an Introduction to Computer Science
Programming - Walter Savitch
30
Resulting GUI for PanelDemo
31
TextArea and TextField classes
  • TextArea defines an area to display text
  • specifies how many lines and how many characters
    per line to display
  • TextField also defines an area to display text
  • but only the number of characters in the line is
    specified
  • the field has only one line
  • For both classes
  • The user can enter text in the field
  • getText reads text entered by the user
  • setText writes text to the field
  • more text can be written to the field than the
    specified size, but only an amount equal to the
    size will be displayed (the scroll bar must be
    used to see the remaining text)
  • initial text can be specified when the object is
    created with new

32
Example TextArea
  • The constructor for TextAreaDemo (Display
    7.14/page 369) creates a panel with a text area
    10 lines by 40 characters
  • The panel color is set to blue and the background
    of the text area to white
  • The panel is placed in the center of the window

Creating a text area (excerpt from Display
7.14/page 369)
33
Example setText and getText
  • Using the same example, TextAreaDemo (Display
    7.14/page 369)
  • Clear the text areatheText.setText("")
  • Read the text entered by the user into String
    instance variable memo1memo1
    theText.getText()

34
Label class
  • Used to label text fields or other components
  • Typical program organization to attach a label to
    a text field
  • Create new panel
  • set panel attributes, e.g. background color and
    panel layout
  • add text field and label
  • Place the panel in the layout

35
Example Label
  • Excerpt from LabelDemo (Display 7.15/page 374)
  • name new TextField(20)
  • namePanel.add(name, "South")
  • Label nameLabel new Label("Enter your name
    here")
  • namePanel.add(nameLabel, "Center")
  • Resulting GUI

Name Tester
X

Enter your name here
A very good name!
A label
Test
Clear
36
Inputting and outputting numbers in the AWT
  • Problem the numbers read from or written to a
    text area are String type but we want numeric
    types
  • all AWT input and output is String
  • Conversion methods are needed
  • to convert from numeric types to String, and
  • to convert String to numeric types

37
Inputting numbers methods, methods, methods, ...
  • Numeric wrapper classes have a valueOf method
    that converts text numbers to the wrapper numeric
    type (Integer, Double, etc.)
  • but we often want the corresponding primitive
    type, so we also need to use the appropriate
    "Value" method (intValue, doubleValue, etc.)
  • and we want to ignore white space before and
    after the input, so the trim method is also used

38
Examplereading an integer from a text area
  • Combining all these results in a rather long
    statement, but it should make sense on careful
    analysis
  • Input exampleRead an integer from text field
    inputOutputField
  • int n Integer.valueOf(inputOutputField.getText()
    .trim()).intValue()

39
Outputting numbers
  • Not so many methods need to be strung together
  • Just use toString to convert a numeric value to
    String, and setText to write it to the text
    area.
  • Output exampleWrite an integer to text field
    inputOutputField
  • int n 31
  • inputOutputField.setText(Integer.toString(n))

40
Adding menus
  • In the AWT menus are not a component but are
    added in ways similar to adding components
  • Three AWT classes are used
  • Menu
  • Menu
  • MenuItem
  • The basic approach is to use an add method to
  • put MenuItems in a Menu and
  • put Menus in a Menu.

41
Examplecreating a menu
Excerpt from MenuDemo constructor (Display
7.18/page 386)
The resulting GUI before and after clicking Memos
is shown on page 388
Note the method to add a menu bar is setMenuBar,
not add
41
Chapter 7
Java an Introduction to Computer Science
Programming - Walter Savitch
42
Inner classes
  • An inner class is a class that is defined inside
    another class
  • A full description is beyond the scope of this
    text
  • However, one situation has already been
    described
  • using the AWT to create GUIs
  • Another simple situation is common and is also
    described
  • helping classes
  • Moving the definition of a helping class inside
    the class definition has two advantages
  • it allows the helping class to access all
    instance variables, including private ones
  • it improves the level of information hiding
  • For these reasons inner classes are often used as
    listeners to handle events fired within the outer
    class

43
Summary ...
  • GUIs are written using event-driven programming
  • In event-driven programming, a user action, like
    a mouse click, generates an event and the that
    event is automatically passed to an
    event-handling program to perform the appropriate
    action.
  • Two main ways to build a GUI with the AWT
  • 1. Use inheritance to create a derived class
    from a preexisting one
  • 2. Add components to a container
  • A window is defined as a derived class of Frame
  • A button is an object of the class button
  • The add method is used to add components to a
    container
  • Components in a container are arranged by a
    layout manager object

44
summary, continued
  • A panel is a container to organize objects inside
    a larger container.
  • Text fields and text areas are used by GUIs for
    input and output of text, including numbers in
    text format
  • methods exist to convert numeric types to and
    from text
  • MenuBars are created by adding Menus and
    MenuItems in a manner similar to putting
    components in containers, but they are not
    members of the classes Container or Components
  • Both buttons and menu items fire action events
    and so should have an ActionListener registered
    with them to respond to the event
Write a Comment
User Comments (0)
About PowerShow.com