© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 3 Designing.

Slides:



Advertisements
Similar presentations
Basic Java – Interface design. Understand: How to use TextPad for Java How to define classes and objects How to create a GUI interface How event-driven.
Advertisements

Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
GUI and Event-Driven Programming Part 2. Event Handling An action involving a GUI object, such as clicking a button, is called an event. The mechanism.
1 Class 8. 2 Chapter Objectives Use Swing components to build the GUI for a Swing program Implement an ActionListener to handle events Add interface components.
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.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 16.1 Test-Driving the Flag Quiz Application.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 20.1 Test-Driving the Screen Saver Application.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
Lab 6: Shapes & Picture Extended Ellipse & Rectangle Classes Stand-Alone GUI Applications.
GUI programming Graphical user interface-based programming.
Chapter 5: Enhancing Classes
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Chapter 8. About the Midterm Exam.. Exam on March 12 Monday (Tentatively) Review on March 7 Wednesday Cover from Chapter 6 Grades will be out before spring.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
 2002 Prentice Hall, Inc. All rights reserved Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
1 Graphical User Interfaces AWT and Swing packages Frames and Panels Components Nested Panels Images Reading for this Lecture: L&L, 3.9 – 3.11.
Copyright © 2002, Systems and Computer Engineering, Carleton University c-Gui3.ppt * Object-Oriented Software Development Part 18-c Building.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
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.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 2 – Welcome Application Introduction to Graphical.
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 27.1 Test-Driving the Drawing Shapes Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 4 – Completing the Inventory Application.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 5.1 Test-Driving the Enhanced Inventory Application.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Graphical User Interface (GUI)
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
GUIs and Events Rick Mercer.
CSC 205 Programming II Lecture 5 AWT - I.
A First Look at GUI Applications
Graphical User Interface (pronounced "gooey")
Java Programming: From Problem Analysis to Program Design,
Ellen Walker Hiram College
Data Structures for Java William H. Ford William R. Topp
Graphical user interface-based programming
CiS 260: App Dev I Chapter 6: GUI and OOD.
Presentation transcript:

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 3 Designing Classes Bret Ford © 2005, Prentice Hall

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The Java Interface An interface is a pure abstract classlike structure. An interface is a pure abstract classlike structure. Contains only public abstract methods and public final static data. Contains only public abstract methods and public final static data. Classes implement the interface rather than extending it. Classes implement the interface rather than extending it. Serves as a template for its implementing classes. Serves as a template for its implementing classes.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The Java Interface (concluded) Interface reference variables can be assigned references from any implementing class. Interface reference variables can be assigned references from any implementing class. Calling a method with an interface reference variable invokes polymorhpism. Calling a method with an interface reference variable invokes polymorhpism. An interface may be implemented by more than one class. An interface may be implemented by more than one class.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Declaring an Interface Use the keyword interface. Example: | public interface InterfaceName { public static final DATA_NAME = ; // method declaration uses only a signature public returnType methodName( ); } Use the keyword interface. Example: | public interface InterfaceName { public static final DATA_NAME = ; // method declaration uses only a signature public returnType methodName( ); }

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing an Interface The relationship between a class and an interface is established by using the keyword implements. The relationship between a class and an interface is established by using the keyword implements. The implementing class must provide method declarations for each method in the interface. The implementing class must provide method declarations for each method in the interface. // class interface declaration public class ClassName implements InterfaceName { }

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The Measurement Interface The Measurement interface is a template for the definition of geometric classes that define the area and perimeter of shapes. The Measurement interface is a template for the definition of geometric classes that define the area and perimeter of shapes. public interface Measurement { public static final double PI = ; double area(); double perimeter(); }

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. public class Circle implements Measurement { private double radius; // creates an instance with // the specified radius public Circle(double radius) { this.radius = radius; } // interface method area() returns // PI * radius (squared) public double area() { return PI * radius * radius; } // interface method perimeter() returns // 2 * PI * radius public double perimeter() { return 2 * PI * radius; } Circle Class

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. // access and update methods public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } // returns a description of the object public String toString() { return "Circle with radius " + radius; } } Circle Class (concluded)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. UML for the Measurement Hierarchy

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Using an Interface Type An interface reference variable can be assigned any object from a class that implements the interface, and polymorphism applies. An interface reference variable can be assigned any object from a class that implements the interface, and polymorphism applies. InterfaceName ref; ImplementingClass obj = new ImplementingClass(...); ref = obj; // calls methodName() in ImplementingClass ref.methodName();

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. public static void resize(Measurement m, double pct) { if (m instanceof Rectangle) { // cast m as a Rectangle Rectangle r = (Rectangle)m; // use setSides() to resize the // length and width r.setSides(r.getLength()*pct, r.getWidth()*pct); }resize()

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. else if (m instanceof Circle) { // cast m as a Circle Circle c = (Circle)m; // use setRadius() to resize the radius c.setRadius(c.getRadius()*pct); } resize() (concluded)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Interface Inheritance Hierarchy A parent interface may be used to derive a child interface. Use the extends keyword. A parent interface may be used to derive a child interface. Use the extends keyword. Example: public interface DiagonalMeasurement extends Measurement { public double diagonal(); } public class Circle implements DiagonalMeasurement { }

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Extending Interface Implementations A class that implements an interface can be extended. The subclass implements the interface also. A class that implements an interface can be extended. The subclass implements the interface also. Example: public class Rectangle implements Measurement {... } public class Square extends Rectangle { <methods area(), perimeter() inherited from Rectangle }

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Multiple Interfaces and Inheritance Java only allows a class to extend one superclass (single inheritance). Java only allows a class to extend one superclass (single inheritance). Some languages like C++ allow a class to inherit multiple superclasses. Some languages like C++ allow a class to inherit multiple superclasses.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Multiple Interfaces and Inheritance (continued)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Java Answer to Multiple Inheritance Allow a superclass to implement multiple interfaces. Allow a superclass to implement multiple interfaces.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc Documentation is needed with any programming language. Documentation is needed with any programming language. The javadoc utility produces HTML documentation for classes and interfaces. The javadoc utility produces HTML documentation for classes and interfaces.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc (continued) Javadoc comments begin with the marker /** and end with the marker */ Javadoc comments begin with the marker /** and end with the marker */ Can use HTML tags in a javadoc comment. Can use HTML tags in a javadoc comment. Javadoc tags that produce HTML include: Javadoc tags that produce HTML for a for a method return method return exception thrown when an error exception thrown when an error occurs

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc Example /** * The Circle class provides measurement * operations for objects that are determined by their radius. */ public class Circle implements Measurement {/** * Creates a circle with the specified radius radius the radius of this object IllegalArgumentException if the argument * is negative. */ public Circle(double radius) {... } /** * Returns the area of the circle. a double having value PI *r (squared). */ public double area() {... } }

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc Output for Circle Class

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc Output for Circle Class (continued)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc Output for Circle Class (continued)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc Output for Circle Class (continued)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc Output for Circle Class (continued)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Design Pattern Documents the solution to a problem in a very general way. Documents the solution to a problem in a very general way. Singleton design pattern describes a model for building a class that may only have one instance. Singleton design pattern describes a model for building a class that may only have one instance.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. public class Dice { // static reference that identifies // the single instance private static Dice dice = null; private Random rnd; private int dice1, dice2; // private constructor is called by // the method getDice() to create // a single instance of the class private Dice() { // create the random number generator rnd = new Random(); } Dice Class as Example of Singleton Design Pattern

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. // if no object currently exists, the // method calls the private constructor // to create an instance; in any case, the // method returns the static reference // variable dice public static Dice getDice() { if (dice == null) { dice = new Dice(); } return dice; } Dice Class as Example of Singleton Design Pattern (continued)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. // toss the dice and update values // for dice1 and dice2 public void toss() { dice1 = rnd.nextInt(6) + 1; dice2 = rnd.nextInt(6) + 1; } // access methods getOne(), getTwo(), // and getTotal()... } Dice Class as Example of Singleton Design Pattern (continued)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. GUI Application Design GUI = "Graphical User Interface". GUI = "Graphical User Interface". GUI Components GUI Components Frame - Main application window Frame - Main application window Panel - Container to which other components are added Panel - Container to which other components are added Label - Displays a string and/or an image Label - Displays a string and/or an image Text field - Allows input/output of text line Text field - Allows input/output of text line Button - Responds to pressing with mouse Button - Responds to pressing with mouse

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Key Components of a GUI Application

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Inheritance Hierarchy for Java GUI Components

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. GUI Application Design Pattern public class DiceToss extends JFrame { public static void main(String[] args) { DiceToss app = new DiceToss(); app.setVisible(true); } // constructor creates components and adds them to the frame public DiceToss() { } // inner class defines an event handler object private class EventHandler implements { } }

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. GUI Design Pattern Import Statements Import statements specify the class libraries that the application will use Import statements specify the class libraries that the application will use import java.awt.*;// original Java AWT import javax.swing;// Swing component classes import java.awt.event.*;// Java event classes and interfaces

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. GUI Design Pattern Application Variables Declare as application variables the GUI components and any data that will be accessed by event handlers, utility methods, and inner classes. Declare as application variables the GUI components and any data that will be accessed by event handlers, utility methods, and inner classes.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Dice Class Variables class DiceToss extends JFrame { // application variables private JPanel panelA, panelB; private JLabel dieLabel1, dieLabel2, totalLabel; private JTextField totalField; private JTextArea totalArea; private JButton tossButton; private Dice d = Dice.getDice(); private ImageIcon[] diePict = {null, new ImageIcon("die1.gif"), new ImageIcon("die2.gif"), new ImageIcon("die3.gif"), new ImageIcon("die4.gif"), new ImageIcon("die5.gif"), new ImageIcon("die6.gif")};... }

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. GUI Application Constructor Initializes frame properties and loads the components. Initializes frame properties and loads the components. Set title with setTitle(titleStr). Set title with setTitle(titleStr). setBounds(posX, posY, width, height) sets the size of the frame and its position on the screen. setBounds(posX, posY, width, height) sets the size of the frame and its position on the screen. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) closes the frame and exits the application when the user clicks the close box in the frame. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) closes the frame and exits the application when the user clicks the close box in the frame.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. GUI Application Constructor (concluded) Components in a frame reside in a region called the content pane. Components in a frame reside in a region called the content pane. Use getContentPane() to access the content pane and assign it to a Container reference variable. Container content = getContentPane(); Use getContentPane() to access the content pane and assign it to a Container reference variable. Container content = getContentPane(); Create and organize components and add them to the content pane. Create and organize components and add them to the content pane.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. public DiceToss() {... // establish the content pane for the window Container content = getContentPane(); content.setLayout(new BorderLayout()); // panel and labels for the two die pictures JPanel panelA = new JPanel(); dieLabel1 = new JLabel(); dieLabel2 = new JLabel(); panelA.add(dieLabel1); panelA.add(dieLabel2); // text area to store results of // successive dice tosses totalArea = new JTextArea(10, 15); DiceToss Constructor

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. // panel with toss button, total label, // and text field for the total // the toss button has an action listener // (see next section) JPanel panelB = new JPanel(); tossButton = new JButton("Toss"); tossButton.addActionListener(new TossEvent()); totalLabel = new JLabel("Total"); totalField = new JTextField(4); panelB.add(tossButton); panelB.add(totalLabel); panelB.add(totalField); DiceToss Constructor (continued)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. // add panels and individual components to the // content pane using compass point constants // for class BorderLayout. // the text area is embedded in a JScrollPane // to add scroll bars content.add(panelA, BorderLayout.NORTH); content.add(new JScrollPane(totalArea), BorderLayout.CENTER); content.add(panelB, BorderLayout.SOUTH); } DiceToss Constructor (concluded)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Event Listeners An event is an action such as a mouse click, a button press, or a keystroke. An event is an action such as a mouse click, a button press, or a keystroke. An event listener is an object that resides in a component and waits for the occurrence of an event and handles the actions required by the event. An event listener is an object that resides in a component and waits for the occurrence of an event and handles the actions required by the event. Add a listener to a component using where Type is the type of the event. Add a listener to a component using addTypeListner(...) where Type is the type of the event.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Action Events An event which indicates that a component-defined action occurred. This event is generated by a component (such as a Button) when the component-specific action occurs (such as being pressed). The event is passed to every ActionListener object that registered to receive such events using the component's addActionListener method An event which indicates that a component-defined action occurred. This event is generated by a component (such as a Button) when the component-specific action occurs (such as being pressed). The event is passed to every ActionListener object that registered to receive such events using the component's addActionListener method

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Action Events (continued) Adds action listener to a component. The parameter is the event handler that responds to the event. void addActionListener(ActionListener handlerObj) Adds action listener to a component. The parameter is the event handler that responds to the event. Normally use a private inner class to define an event handler. An inner class has access to all the variables in the outer class and can update them. Normally use a private inner class to define an event handler. An inner class has access to all the variables in the outer class and can update them.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Action Events (concluded) An action listener event handling class must implement the ActionListener interface. The interface has only one method Invoked when an action occurs An action listener event handling class must implement the ActionListener interface. The interface has only one method void actionPerformed(ActionEvent ae) Invoked when an action occurs

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Action Event Sequence

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. private class TossEvent implements ActionListener { public void actionPerformed(ActionEvent ae) { d.toss(); dieLabel1.setIcon(diePict[d.getOne()]); dieLabel2.setIcon(diePict[d.getTwo()]); totalArea.append("Total is " + d.getTotal() + "\n"); totalField.setText("" + d.getTotal()); } DiceToss Event Handler Class