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

Slides:



Advertisements
Similar presentations
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Advertisements

Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
Graphical User Interfaces (Part IV)
Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
1 Chapter 12 l Event-Driven Programming and GUIs l Swing Basics and a Simple Demo Program l Layout Managers l Buttons and Action Listeners l Container.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Java Programming, 3e Concepts and Techniques Chapter 5 Arrays, Loops, and Layout Managers Using External Classes.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Chapter Day 10. © 2007 Pearson Addison-Wesley. All rights reserved4-2 Agenda Day 10 Questions from last Class?? Problem set 2 posted  10 programs from.
Chapter 121 Window Interfaces Using Swing Chapter 12.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter Day 9. © 2007 Pearson Addison-Wesley. All rights reserved4-2 Agenda Day 8 Questions from last Class?? Problem set 2 posted  10 programs from.
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
Java Programming Chapter 10 Graphical User Interfaces.
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 16: Java Applets & AWT Fundamentals of Web Programming.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
Copyright © Curt Hill First Window Builder Program Easy GUIs in Eclipse.
Session 10 CannonGame and Event-driven Programming.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 13 : Swing I King Fahd University of Petroleum & Minerals College of Computer Science.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Timer class and inner classes. Processing timer events Timer is part of javax.swing helps manage activity over time Use it to set up a timer to generate.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action.
The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT features include: a rich set of user interface components; a.
Computer Programming with JAVA Chapter 7. Event-Driven Programming Using the AWT Event-Driven Programming GUIs and the AWT Simple Window Interfaces Components,
Object Oriented Programming.  Interface  Event Handling.
SEEM3460 Tutorial GUI in Java. Some Basic GUI Terms Component (Control in some languages) the basic GUI unit something visible something that user can.
Chapter 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 12 l Event-Driven Programming and GUIs l Swing Basics and.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
CSC 205 Programming II Lecture 7 AWT – Event Handling & Layout.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
CSC 205 Programming II Lecture 5 AWT - I.
A First Look at GUI Applications
“Form Ever Follows Function” Louis Henri Sullivan
Graphical User Interface (pronounced "gooey")
Java Programming: From Problem Analysis to Program Design,
Ellen Walker Hiram College
Chap 7. Building Java Graphical User Interfaces
Chapter 13: Advanced GUIs and Graphics
Graphical User Interfaces -- Introduction
Timer class and inner classes
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

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

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

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

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!

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

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)

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

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

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

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

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

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

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)

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

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:

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 :

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

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 :

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

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

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"

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:

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:

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.

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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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

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

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

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