Laying Out a User Interface

Một phần của tài liệu sams teach yourselfa java in 24 hours 6th edition (Trang 164 - 178)

PART IV: Programming a Graphical User Interface

HOUR 14: Laying Out a User Interface

ptg7068951 At the top is the Objectclass.JApplethas five superclasses above it in the

hierarchy: Applet,Panel,Container,Component, and Object.

TheJAppletclass inherits attributes and behavior from each of these class- es because each is directly above it in the hierarchy of superclasses. JApplet does not inherit anything from the five green classes in Figure 12.1, which includeDialogandFrame, because they are not above it in the hierarchy.

If this seems confusing, think of the hierarchy as a family tree. JApplet inherits from its parent, the parent’s parent, and on upward. It even might inherit some things from its great-great-great-grandparent, Object. The JAppletclass doesn’t inherit from its siblings or its cousins, however.

Creating a new class boils down to the following task: You only have to define the ways in which it is different from an existing class. The rest of the work is done for you.

Inheriting Behavior and Attributes

The behavior and attributes of a class are a combination of two things: its own behavior and attributes and all the behavior and attributes it inherits from its superclasses.

The following are some of the behavior and attributes of JApplet: . Theequals()method determines whether a JAppletobject has the

same value as another object.

WINDOW

DIALOG

FILEDIALOG CONTAINER COMPONENT

OBJECT

PANEL

APPLET

JAPPLET SCROLLPANE

FRAME The family tree of the JApplet

class.

ptg7068951

Establishing Inheritance 157

. The setBackground()method sets the background color of the applet window.

. The add()method adds user interface components such as buttons and text fields to the applet.

. The setLayout()method defines how the applet’s graphical user interface is organized.

The JAppletclass can use all these methods, even though setLayout()is the only one it didn’t inherit from another class. The equals()method is defined in Object, setBackground()comes from Component, and add() comes from Container.

Overriding Methods

Some methods defined in the JAppletclass of objects also are defined in one of its superclasses. As an example, the update()method is part of both the JAppletclass and the Componentclass. When a method is defined in a subclass and its superclass, the subclass method is used. This enables a subclass to change, replace, or completely wipe out some of the behavior or attributes of its superclasses. In the case of update(), the purpose is to wipe out some behavior present in a superclass.

Creating a new method in a subclass to change behavior inherited from a superclass is called overridingthe method. You need to override a method any time the inherited behavior produces an undesired result.

Establishing Inheritance

A class is defined as the subclass of another class using the extendsstate- ment, as in the following:

class AnimatedLogo extends JApplet { // behavior and attributes go here }

The extendsstatement establishes the AnimatedLogoclass of objects as a subclass of JApplet. As you see during Hour 17, “Creating Interactive Web Programs,” all Swing applets must be subclasses of JApplet. They need the functionality this class provides to run when presented on a web page.

One method that AnimatedLogomust override is the paint()method, which is used to draw everything within the program’s window. The

ptg7068951 paint()method, implemented by the Componentclass, is passed all the

way down to AnimatedLogo. However, the paint()method does not do anything. It exists so that subclasses of Componenthave a method they can use when something must be displayed.

To override a method, you must declare the method in the same way it was declared in the superclass from which it was inherited. Apublicmethod must remain public, the value sent back by the method must be the same, and the number and type of arguments to the method must not change.

The paint()method of the Componentclass begins as follows:

public void paint(Graphics g) {

When AnimatedLogooverrides this method, it must begin with a statement like this:

public void paint(Graphics screen) {

The only difference lies in the name of the Graphicsobject, which does not matter when determining if the methods are created in the same way.

These two statements match because the following things match:

. Both paint()methods are public.

. Both methods return no value, as declared by the use of the void statement.

. Both have a Graphicsobject as their only argument.

Using this and super in a Subclass

Two keywords that are extremely useful in a subclass are thisand super. As you learned during the previous hour, the thiskeyword is used to refer to the current object. When you’re creating a class and you need to refer to the specific object created from that class, you can use this, as in the following statement:

this.title = “Cagney”;

This statement sets the object’s titlevariable to the text “Cagney.”

The superkeyword serves a similar purpose: It refers to the immediate superclass of the object. You can use superin several different ways:

. To refer to a constructor method of the superclass, as in

ptg7068951

Working with Existing Objects 159

. To refer to a variable of the superclass, as in super.hawaii = 50 . To refer to a method of the superclass, as in super.dragnet() One way you use the superkeyword is in the constructor method of a sub- class. Because a subclass inherits the behavior and attributes of its super- class, you have to associate each constructor method of that subclass with a constructor method of its superclass. Otherwise, some of the behavior and attributes might not be set up correctly, and the subclass isn’t able to function properly.

To associate the constructors, the first statement of a subclass constructor method must be a call to a constructor method of the superclass. This requires the superkeyword, as in the following statements:

public readFiles(String name, int length) { super(name, length);

}

This example is the constructor method of a subclass, which is using super(name, length)to call a comparable constructor in its superclass.

If you don’t use superto call a constructor method in the superclass, Java automatically calls super()with no arguments when the subclass con- structor begins. If this superclass constructor doesn’t exist or provides unexpected behavior, errors result, so it’s better to call a superclass con- structor yourself.

Working with Existing Objects

OOP encourages reuse. If you develop an object for use with one Java pro- gramming project, it should be possible to incorporate that object into another project without modification.

If a Java class is well designed, it’s possible to make that class available for use in other programs. The more objects available for use in your pro- grams, the less work you have to do when creating your own software. If there’s an excellent spell-checking object that suits your needs, you can use it instead of writing your own. Ideally, you can even give your boss a false impression about how long it took to add spell-checking functionality to your project, and use this extra time to make personal long-distance calls from the office.

NOTE

The author of this book, like many in his profession, is self- employed and works out of his home. Please keep this in mind when evaluating his advice on how to conduct yourself in the workplace.

ptg7068951 When Java was first introduced, the system of sharing objects was largely

an informal one. Programmers developed their objects to be as independ- ent as possible and protected them against misuse through the use of pri- vate variables and public methods to read and write those variables.

Sharing objects becomes more powerful when there’s a standard approach to developing reusable objects.

The benefits of a standard include the following:

. There’s less need to document how an object works because anyone who knows the standard already knows a lot about how it functions.

. You can design development tools that follow the standard, making it possible to work more easily with these objects.

. Two objects that follow the standard are able to interact with each other without special programming to make them compatible.

Storing Objects of the Same Class in Vectors

An important decision to make when writing a computer program is where to store data. In the first half of this book, you’ve found three useful places to keep information: basic data types such as intand char, arrays, and Stringobjects.

Any Java class can hold data. One of the most useful is Vector, a data structure that holds objects of the same class.

Vectors are like arrays, which also hold elements of related data, but they can grow or shrink in size at any time.

The Vectorclass belongs to the java.utilpackage of classes, one of the most useful in the Java class library. An importstatement makes it avail- able in your program:

import java.util.Vector;

A vector holds objects that either belong to the same class or share the same superclass. They are created by referencing two classes—the Vector class and the class the vector holds.

ptg7068951 Storing Objects of the Same Class in Vectors 161

The name of the class held by the vector is placed within <and >charac- ters, as in this statement:

Vector<String> victor = new Vector<String>();

The preceding statement creates a vector that holds strings. Identifying a vector’s class in this manner utilizes generics, a way to indicate the kind of objects a data structure like vector holds. If you are using vectors with an older version of Java, you’d write a constructor like this:

Vector victor = new Vector();

Although you can still do this, generics make your code more reliable because they give the compiler a way to prevent you from misusing a vec- tor. If you attempt to put an Integerobject in a vector that’s supposed to hold Stringobjects, the compiler fails with an error.

Unlike arrays, vectors aren’t created with a fixed number of elements they hold. The vector is created with 10 elements. If you know you’re storing a lot more objects than that, you can specify a size as an argument to the constructor. Here’s a statement that creates a 300-element vector:

Vector<String> victoria = new Vector<String>(300);

You can add an object to a vector by calling its add()method, using the object as the only argument:

victoria.add(“Vance”);

victoria.add(“Vernon”);

victoria.add(“Velma”);

You add objects in order, so if these are the first three objects added to victoria, element 0 is “Vance”, element 1 is “Vernon”, and element 2 is

“Velma”.

You retrieve elements from vectors by calling their get()method with the element’s index number as the argument:

String name = victoria.get(1);

This statement stores “Vernon” in the namestring.

To see if a vector contains an object in one of its elements, call its contains()method with that object as an argument:

if (victoria.contains(“Velma”)) { System.out.println(“Velma found”);

}

ptg7068951 You can remove an object from a vector using itself or an index number:

victoria.remove(0);

victoria.remove(“Vernon”);

These two statements leave “Velma” as the only string in the vector.

Looping Through a Vector

Java includes a specialforloop that makes it easy to load a vector and examine each of its elements in turn.

This loop has two parts, one less than the forloops you learned about in Hour 8, “Repeating an Action with Loops.”

The first part is the initialization section: the class and name of a variable that holds each object retrieved from the vector. This object should belong to the same class that holds the vector.

The second part identifies the vector.

Here’s code that loops through the victoriavector, displaying each name to the screen:

for (String name : victoria) { System.out.println(name);

}

The hour’s first project takes vectors and the special forloop for a spin, presenting a list of strings in alphabetical order. The list comes from an array and command-line arguments.

With your Java24 project open within NetBeans, choose File, New File, and then create a new Empty Java File named StringLister. Enter Listing 12.1 in the source editor and save the file.

LISTING 12.1 The Full Text of StringLister.java 1: import java.util.*;

2:

3: public class StringLister {

4: String[] names = { “Spanky”, “Alfalfa”, “Buckwheat”, “Daria”, 5: “Stymie”, “Marianne”, “Scotty”, “Tommy”, “Chubby” };

6:

7: public StringLister(String[] moreNames) { 8: Vector<String> list = new Vector<String>();

9: for (int i = 0; i < names.length; i++) { 10: list.add(names[i]);

11: }

12: for (int i = 0; i < moreNames.length; i++) {

ptg7068951 Storing Objects of the Same Class in Vectors

13: list.add(moreNames[i]);

14: }

15: Collections.sort(list);

16: for (String name : list) { 17: System.out.println(name);

18: } 19: } 20:

21: public static void main(String[] args) {

22: StringLister lister = new StringLister(args);

23: } 24: }

Before you run the. application (choose Run, Run File), you should use the Run, Set Project Configuration, Customize command to set the main class toStringListerand the argument to one or more names separated by spaces, such as Jackie Mickey Farina Woim.

The names specified at the command line are added to the names stored in an array in Lines 4–5. Because the total number of names is not known until the program runs, a vector serves as a better storage place for these strings than an array.

The vector’s strings are sorted in alphabetical order using a method of the Collectionsclass:

Collections.sort(list);

This class, like Vector, belongs to the java.utilpackage. Vectors and other useful data structures are called collections in Java.

When you run the program, the output should be a list of names in alpha- betical order (see Figure 12.2). The flexible size of vectors enables your additional names to be added to the data structure and sorted along with the others.

The output of the StringLister program.

ptg7068951

Creating a Subclass

To see an example of inheritance at work, in the next project you create a class called Point3Dthat represents a point in three-dimensional space. You can express a two-dimensional point with an (x,y) coordinate. Applets use an (x,y) coordinate system to determine where text and graphics should be displayed.

Three-dimensional space adds a third coordinate, which can be called z.

The Point3Dclass of objects should do three things:

. Keep track of an object’s (x,y,z) coordinate

. Move an object to a new (x,y,z) coordinate when needed

. Move an object by a certain amount of x, y, and z values as needed Java already has a standard class that represents two-dimensional points;

it’s calledPoint.

It has two integer variables called xand ythat store a Pointobject’s (x,y) location. It also has a move()method to place a point at the specified loca- tion, and a translate()method to move an object by an amount of x and y values.

In the Java24 projects in NetBeans, create a new empty file called Point3D and enter the text of Listing 12.2 into the file. Save it when you’re done.

LISTING 12.2 The Full Text of Point3D.java 1: import java.awt.*;

2:

3: public class Point3D extends Point { 4: public int z;

5:

6: public Point3D(int x, int y, int z) { 7: super(x,y);

8: this.z = z;

9: } 10:

11: public voidmove(int x, int y, int z) { 12: this.z = z;

13: super.move(x, y);

14: } 15:

16: public voidtranslate(int x, int y, int z) { 17: this.z += z;

18: super.translate(x, y);

19: } 20: }

ptg7068951

Creating a Subclass 165

The Point3Dclass does not have a main()block statement, so you cannot run it with a Java interpreter, but you can use it in Java programs anywhere a three-dimensional point is needed.

The Point3Dclass only has to do work that isn’t being done by its superclass, Point. This primarily involves keeping track of the integer variable zand receiving it as an argument to the move()method, translate()method, and Point3D()constructor method.

All the methods use the keywords superand this. The thisstatement is used to refer to the current Point3Dobject, so this.z = z;in Line 8 sets the object variable zequal to the zvalue that is sent as an argument to the method in Line 6.

The superstatement refers to the current object’s superclass, Point. It is used to set variables and call methods that are inherited by Point3D. The statement super(x,y)in Line 7 calls the Point(x,y)constructor in the superclass, which then sets the (x,y) coordinates of the Point3Dobject. Because Point already is equipped to handle the x and y axes, it would be redundant for the Point3Dclass of objects to do the same thing.

To test out the Point3Dclass you have compiled, create a program that uses Pointand Point3Dobjects and moves them around. Create a new file in NetBeans called PointTesterand enter Listing 12.3 into it. The file compiles automatically when it is saved.

LISTING 12.3 The Full Text of PointTester.java 1: import java.awt.*;

2:

3: class PointTester {

4: public static void main(String[] args) { 5: Point object1 = new Point(11,22);

6: Point3D object2 = new Point3D(7,6,64);

7:

8: System.out.println(“The 2D point is located at (“ + object1.x 9: + “, “ + object1.y + “)”);

10: System.out.println(“\tIt’s being moved to (4, 13)”);

11: object1.move(4,13);

12: System.out.println(“The 2D point is now at (“ + object1.x 13: + “, “ + object1.y + “)”);

14: System.out.println(“\tIt’s being moved -10 units on both the x “ 15: + “and y axes”);

16: object1.translate(-10,-10);

17: System.out.println(“The 2D point ends up at (“ + object1.x 18: + “, “ + object1.y + “)\n”);

19:

ptg7068951

20: System.out.println(“The 3D point is located at (“ + object2.x 21: + “, “ + object2.y + “, “ + object2.z + “)”);

22: System.out.println(“\tIt’s being moved to (10, 22, 71)”);

23: object2.move(10,22,71);

24: System.out.println(“The 3D point is now at (“ + object2.x 25: + “, “ + object2.y + “, “ + object2.z + “)”);

26: System.out.println(“\tIt’s being moved -20 units on the x, y “ 27: + “and z axes”);

28: object2.translate(-20,-20,-20);

29: System.out.println(“The 3D point ends up at (“ + object2.x 30: + “, “ + object2.y + “, “ + object2.z + “)”);

31: } 32: }

When you run the file by choosing Run, Run File, you see the output shown in Figure 12.3 if the program compiled properly. If not, look for the red icon alongside the source editor that indicates the line that triggered an error.

LISTING 12.3 Continued

FIGURE 12.3

The output of the PointTester program.

Summary

When people talk about the miracle of birth, they’re probably not speaking of the way a superclass in Java can give birth to subclasses or the way behavior and attributes are inherited in a hierarchy of classes.

If the real world worked the same way that OOP does, every descendant of Mozart could choose to be a brilliant composer. All descendants of Mark Twain could be poetic about Mississippi riverboat life. Every skill your ances- tors worked to achieve would be handed to you without an ounce of toil.

On the scale of miracles, inheritance isn’t quite up to par with continuing the existence of a species or throwing consecutive no-hitters. However, it’s an effective way to design software with a minimum of redundant work.

ptg7068951

Workshop 167

Q&A

Q. Most Java programs we’ve created up to this point have not used

extendsto inherit from a superclass. Does this mean they exist out- side of the class hierarchy?

A. All classes you create in Java are part of the hierarchy because the default superclass for the programs you write is Objectwhen you aren’t using the extendskeyword. The equals()andtoString()methods of all classes are part of the behavior that automatically is inherited from

Object.

Q. Why do people yell “eureka!” when they’ve discovered something?

A. Eureka is borrowed from ancient Greek, where it meant “I have found it!” The phrase was supposedly exclaimed by the Greek scholar Archimedes when he stepped into a bath.

What did the Greek discover in the bath? The rising water level, which led him to understand that the volume of displaced water must equal the volume of his body parts.

The story about Archimedes was spread two centuries later by Vitruvius in his multivolume De Architectura, a book about architecture.

“Eureka” has been in the California state seal since 1849, referring to the discovery of gold near Sutter’s Mill a year earlier.

Workshop

To determine what kind of knowledge you inherited from the past hour’s work, answer the following questions.

Quiz

1. If a superclass handles a method in a way you don’t want to use in the subclass, what can you do?

A. Delete the method in the superclass.

B. Override the method in the subclass.

C. Write a nasty letter to the editor of the San Jose Mercury News hoping that Java’s developers read it.

Một phần của tài liệu sams teach yourselfa java in 24 hours 6th edition (Trang 164 - 178)

Tải bản đầy đủ (PDF)

(429 trang)