Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 7 l Event-Driven Programming »GUIs and the AWT l Simple Window.

Similar presentations


Presentation on theme: "Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 7 l Event-Driven Programming »GUIs and the AWT l Simple Window."— Presentation transcript:

1 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 7 l Event-Driven Programming »GUIs and the AWT l Simple Window Interfaces l Components, Containers, and Layout Managers l Panels and Text Components l Adding Menus l Inner Classes Event-Driven Programming Using the AWT

2 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 2 Event-Driven Programming l A different approach to program design l Programs react to events, e.g. »mouse click »key press »menu selection »button selection »message sent from printer »etc. l 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 l An event is an object

3 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 3 AWT l Abstract Window Toolkit l Implements GUI l A standard part of Java l Not fancy, but adequate l Makes extensive use of inheritance l Based on events and event handlers l Firing an event: when an object generates an event l 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 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 4 WARNING! Programs that use the AWT can hang the computer Save your work before running a program using the AWT!

5 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 5 Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 5 Example: include the AWT library & extend Frame l The 1st two lines are needed when you use the AWT library l 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):

6 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 6 A word about displays: pixels l Displays are organized as a 2- dimensional grid of pixels l pixel: picture element »the smallest "addressable" unit of a screen l "Address" = coordinates »(width, height) l The origin has coordinates (0,0) and is in upper left »increasing width is to right »increasing height is down (0, 0) Increasing width (x direction) Increasing height (y direction) (75, 100)

7 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 7 Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 7 Example: define paint method; Graphics class and drawString 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 Additional method paint (Display 7.1/page 329):

8 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 8 Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 8 Example: define system constants Conventional style of declaring system constants (Display 7.1/page 329): l 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 l 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

9 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 9 Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 9 Example: display window; define and register listeners The main method (Display 7.1/page 329): 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

10 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 10 Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 10 Example: windowAdapter abstract class and System.exit windowDestroyer definition (Display 7.2/page 332): 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 l "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

11 Chapter 7Java: 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 l etc. - see Display 7.7/page 344

12 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 12 Two principle ways to create new classes from old ones One method: Inheritance Use extend to create a custom window based on an existing class l For example: … FirstWindow extends Frame Another: Container class l Use a container class Use the add method to place items in it »Items placed in a container class are called components l 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 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 13 AWT container class AWT container classes: Window, Panel, Frame »All three are descendents of the class Container l 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 l 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 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 14 Hierarchy of AWT classes Display 7.9/page 350 Object MenuComponentComponent ContainerButtonMenubar MenuItem Window Label TextComponent Panel Menu FrameTextAreaTextField Class Abstract Class Key: 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. AWT

15 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 15 Example: creating a window using a container class and components ButtonDemo (Display 7.8/page 347) l The constructor is shown in box at right l Note the code to create and add buttons (shown in blue) ButtonDemo constructor:

16 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 16 Example: drawString and repaint 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 Using a String instance variable in drawString :

17 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 17 Example: action listeners l 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 { } 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 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 18 actionPerformed method l 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 actionPerformed method for ButtonDemo :

19 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 19 Layout managers Three basic layout managers provided with AWT: 1. FlowLayout 2. BorderLayout 3. GridLayout l There are others but they are not covered in this text

20 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 20 FlowLayout To create a FlowLayout object: setLayout(new FlowLayout()); l 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 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 21 BorderLayout To create a BorderLayout object: setLayout(new BorderLayout()); l Components can be placed in any one of five regions »"North" »"South" »"East" »"West" »"Center"

22 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 22 Example: BorderLayout In the constructor for some container object: setLayout(new BorderLayout()); add(new Button("Up"),"North"); add(new Button("Down"),"South"); add(new Button("Right"),"East"); add(new Button("Left"),"West"); add(new Button("Straight ahead"),"Center"); Up Down LeftRight Straight ahead The result:

23 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 23 GridLayout l Arranges components in a two-dimensional grid (rows and columns) l Each entry is the same size For a grid with two rows and three columns: setLayout(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 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 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 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 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 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 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 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 27 More about interfaces l Interfaces are just a collection of undefined methods l A Java class can be derived from only one base class but can implement more than one interface l 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 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 28 The Panel class l A container class to group objects Used to subdivide a Frame into different areas l 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 l 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 l Example code: Display 7.13/page 366

29 Example: Panel Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 29 create panel place panel in GUI PanelDemo constructor from Display 7.13/page 366

30 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 30 Resulting GUI for PanelDemo Button Demonstration X Watch me! RedGreen

31 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 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 l 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 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 32 Example: TextArea The constructor for TextAreaDemo (Display 7.14/page 369) creates a panel with a text area 10 lines by 40 characters l The panel color is set to blue and the background of the text area to white l The panel is placed in the center of the window Creating a text area (excerpt from Display 7.14/page 369):

33 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 33 Example: setText and getText Using the same example, TextAreaDemo (Display 7.14/page 369): Clear the text area: theText.setText(""); Read the text entered by the user into String instance variable memo1 : memo1 = theText.getText();

34 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 34 Label class l Used to label text fields or other components l 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 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 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 TestClear Enter your name here: A very good name! A label

36 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 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 l Conversion methods are needed »to convert from numeric types to String, and »to convert String to numeric types

37 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 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 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 38 Example: reading an integer from a text area Combining all these results in a rather long statement, but it should make sense on careful analysis: Input example Read an integer from text field inputOutputField : int n = Integer.valueOf(inputOutputField.getText().trim()).intValue();

39 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 39 Outputting numbers l 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 example Write an integer to text field inputOutputField : int n = 31; inputOutputField.setText(Integer.toString(n));

40 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 40 Adding menus l In the AWT menus are not a component but are added in ways similar to adding components l Three AWT classes are used »Menu »MenuItem The basic approach is to use an add method to »put MenuItem s in a Menu and »put Menu s in a Menu.

41 Example: creating a menu Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 41 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

42 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 42 Inner classes l An inner class is a class that is defined inside another class l A full description is beyond the scope of this text l However, one situation has already been described: using the AWT to create GUIs l Another simple situation is common and is also described: helping classes l 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 l For these reasons inner classes are often used as listeners to handle events fired within the outer class

43 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 43 Summary... l GUIs are written using event-driven programming l 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. l 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 l Components in a container are arranged by a layout manager object

44 Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 44 … summary, continued l A panel is a container to organize objects inside a larger container. l 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 MenuBar s are created by adding Menu s and MenuItem s 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


Download ppt "Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 7 l Event-Driven Programming »GUIs and the AWT l Simple Window."

Similar presentations


Ads by Google