Sie sind auf Seite 1von 76

Program Modules

Program development requires that large programs are divided into smaller program modules to be manageable. This is the principle of divide and conquer.

Structured Programming
Structured Programming is an organized
style of programming that places emphasis on modular programming, which aids testing, debugging and modifying. In structured programming, modules are procedures and functions that process external data passed by parameters.

Casual OOP Definition


Object Oriented Programming is a programming
style with heavy emphasis on program reliability through modular programming.

In object oriented programming, modules contain both the data and subroutines that process the data. In Java the modules are called classes and the process-subroutines are smaller modules called methods.

Formal OOP Definition


Object Oriented Programming is a style
of programming that incorporates program development in a language with the following three OOP traits: Encapsulation Polymorphism Inheritance

OOP Example
A car could be an object in Java. Objects have attributes and methods. Car Attributes Make & Model Color # of Doors # of Seats Car Methods Drive Park Reverse Tow

Encapsulation
Car Attributes
Make & Model Color # of Doors # of Seats

Car Methods
Drive Park Reverse Tow

Encapsulation is the process of placing a data structures data (attributes) with the methods (actions) that act upon the data inside the same module, called a class in Java.

Inheritance

Inheritance is the process of using features (both


attributes and actions) from an established higher class. The higher class is called the superclass. The lower class is called the subclass. A Truck is a Car with 4WD, big tires, and a bed. A Limo is a very long luxury Car with many seats. A Racecar is a Car with 1 seat, a very powerful engine, and a number painted on the side.

Polymorphism
If we review our Algebra we should remember: A monomial is a single term like: 3x A binomial is 2 terms like: 3x + 7 A polynomial is many terms like: x2 + 3x + 7
The prefix Poly means many. Polymorphism means many forms.

Polymorphism allows a single accessing feature,


such as an operator, method or class identifier, to have many forms.

The details of this powerful OOP concept will come in a later chapter.

Class
A class is a data type that encapsulates both data and the methods that act upon the data.
A class is a template for the construction of objects.

Object or Instance
An object is one instance of a class. A class is a type and an object is a variable. Cat is a class and Fluffy is an object or one instance of the Cat class. Objects can be discussed in a general sense, such as in Object Oriented Programming. This causes confusion between Object the concept and object the instance of a class. There is a tendency to use instance when referring to one variable example of a class.

Attributes or Instance Variables


The data components of a class are the class attributes and they are also called instance variables. In the majority of classes instance variables should only be accessed by methods of the same class.

Methods
Methods are action modules that process data.
In other languages such modules may be called subroutines, procedures and functions. In Java the modules are called methods. They are declared inside a class module and process the instance variables.

Instantiation
Instantiation is the moment or instance that
memory is allocated for a specific object of a class. Statements like: the construction of an object the definition of an object the creation of an object
all have the same meaning as the instantiation of an object.

// Java2401.java // Stage-1 of the Person class. // Only the Person class data attributes are declared. // Each stage of the Person class will have its own number to // distinguish between the different stages. public class Java2401 { public static void main(String args[]) { System.out.println("Java 2401.java, Person Class, Stage 1\n"); Person01 person = new Person01(); System.out.println(); } }

class Person01 { String name; int yearBorn; int education; }

Class Declaration Location


In most cases a class declaration is located outside any other class declaration. It is possible to declare one class inside another class (inner class), which will be explained later.

// Java2402.java // Stage-2 of the Person class. // This stage adds a default "no-parameter" constructor to the Person class. public class Java2402 { public static void main(String args[]) { System.out.println("Java2402.java, Person Class, Stage 2\n"); Person02 person = new Person02(); System.out.println(); } } class Person02 { String name; int yearBorn; int education; Person02() { name = "John Doe"; yearBorn = 1980; education = 0; System.out.println("Default Object Constructed"); }

Instantiation & Construction


An object is created with the new operator. The special method that is called during the instantiation of a new object is called a constructor.

Constructor Notes
A constructor is a method with the same identifier as the class. Constructors are neither void nor return methods. A constructor is called during the instantiation of an object. Constructors without parameters are default constructors.

// Java2403.java Stage-3 of the Person class. // This stage accesses Person data directly, which is very poor OOP design // by violating encapsulation, which may cause side effects. public class Java2403 { public static void main(String args[]) { System.out.println("Java2403.java, Person Class, Stage 3\n"); Person03 person = new Person03(); System.out.println("name: " + person.name); System.out.println("yearBorn: " + person.yearBorn); System.out.println("education: " + person.education); System.out.println(); } } class Person03 { String name; int yearBorn; int education; Person03() { name = "John Doe"; yearBorn = 1980; education = 0; System.out.println("Default Object Constructed\n"); } }

// Java2404.java Stage-4 of the Person class. // In this program direct access to class data is denied by declaring all // class data private. This program will not compile. public class Java2404 { public static void main(String args[]) { System.out.println("Java2404.java, Person Class, Stage 4\n"); Person04 person = new Person04(); System.out.println("name: " + person.name); System.out.println("yearBorn: " + person.yearBorn); System.out.println("education: " + person.education); System.out.println(); } } class Person04 {

private String name; private int yearBorn; private int education; public Person04()
{ name = "John Doe"; yearBorn = 1980; education = 0; System.out.println("Default Object Constructed\n"); }

// Java2405.java Stage-5 of the Person class. // The private data of the Person class is now properly accessed with // public member getmethods of the Person class. public class Java2405 { public static void main(String args[]) { System.out.println("Java2405.java, Person Class, Stage 5\n"); Person05 person = new Person05(); System.out.println("name: " + person.getName()); System.out.println("yearBorn: " + person.getYearBorn()); System.out.println("education: " + person.getEducation()); System.out.println(); } } class Person05 { private String name; private int yearBorn; private int education; public Person05() { System.out.println("Calling Default Constructor\n"); name = "John Doe"; yearBorn = 1980; education = 0; }

public int getYearBorn() public String getName() public int getEducation()

{ return yearBorn; } { return name; } { return education; }

private & public class Members


The principle of encapsulation requires that object data members are only accessed by methods of the same object.

Private class members of some object x can only be


accessed by methods of the same x object.

Public class members of some object x can be accessed by


any client of object x. Data attributes of a class should be declared private. Methods of a class are usually declared public, but there are special helper methods that may also be declared private. Helper methods will be demonstrated later in this chapter.

// Java2406.java // Stage-6 of the Person class. // This stage adds a second "parameter-constructor" to the Person class. public class Java2406 { public static void main(String args[]) { System.out.println("Java2406.java, Person Class, Stage 6\n");

Person06 person1 = new Person06();

// default object

System.out.println("name: " + person1.getName()); System.out.println("yearBorn: " + person1.getYearBorn()); System.out.println("education: " + person1.getEducation()); System.out.println();

Person06 person2 = new Person06("Sue",1972,16); // parameter object


System.out.println("name: " + person2.getName()); System.out.println("yearBorn: " + person2.getYearBorn()); System.out.println("education: " + person2.getEducation()); System.out.println(); } }

class Person06 { private String name; private int yearBorn; private int education; public Person06() { System.out.println("Default Object Constructed\n"); name = "John Doe"; yearBorn = 1980; education = 0; }

public Person06(String n, int y, int e) { System.out.println("Parameter Object Constructed\n"); name = n; yearBorn = y; education = e; }
public int getYearBorn() public String getName() public int getEducation() { return yearBorn; } { return name; } { return education; }

// Java2407.java // Stage-7 of the Person class. // This program shows how a program can be separated into multiple files, // which in this case are the Person07.java and Java2407 files. // The result is the same as the Java2406.java program. public class Java2407 { public static void main(String args[]) { System.out.println("Java2407.java, Person Class, Stage 7\n"); Person07 person1 = new Person07(); System.out.println("name: " + person1.getName()); System.out.println("yearBorn: " + person1.getYearBorn()); System.out.println("education: " + person1.getEducation()); System.out.println(); Person07 person2 = new Person07("Sue",1972,16); System.out.println("name: " + person2.getName()); System.out.println("yearBorn: " + person2.getYearBorn()); System.out.println("education: " + person2.getEducation()); System.out.println(); }

// Person07.java // This file is only the Person class declaration. You cannot execute this file. // You can compile this file to get a Person07.class bytecode file. // This file supports the executable Java2407.java file. public class Person07 { private String name; private int yearBorn; private int education; public Person07() { System.out.println("Default Object Constructed\n"); name = "John Doe"; yearBorn = 1980; education = 0; } public Person07(String n, int y, int e) { System.out.println("Parameter Object Constructed\n"); name = n; yearBorn = y; education = e; } public int getYearBorn() { return yearBorn; } public String getName() { return name; } public int getEducation() { return education; } }

Working with Multiple Files


Create a separate file for each class in the program or at least a file that is manageable in size with several small classes. Make sure there is only one file with a main method, known as the main file or driver class. Place all the files in the same folder and compile the driver class, which will result in compiling all other classes, or compile each file separately.

Execute the entire program by executing the main driver class.


When programs become large with multiple classes that are placed in multiple files a project should be used.

// Java2408.java Stage-8 of the Person class. // This stage adds "Set Methods" that alter private data of a class during program // execution. It also adds a <showData> method to display all the data with a single call. import java.util.Scanner; public class Java2408 { public static void main (String args[]) { System.out.println("Java2408.java, Person Class, Stage 8\n"); Scanner input = new Scanner(System.in); Person08 person = new Person08(); person.showData(); System.out.print("Enter name ===>> "); person.setName(input.nextLine()); System.out.print("Enter year born ===>> "); person.setYearBorn(input.nextInt()); System.out.print("Enter education ===>> "); person.setEducation(input.nextInt()); System.out.println(); person.showData(); System.out.println(); } }

// Person08.java // Stage 8 of the Person class adds Set Methods that alter private data // information during program execution. There is also a ShowData method // added that displays all the Person class information with one method call. // This file supports the Java2408.java file. public class Person08 { ///// PRIVATE PERSON ATTRIBUTES //////////////////////////////////////////////////// private String name; private int yearBorn; private int education; ///// GET (ACCESSOR) METHODS //////////////////////////////////////////////////////// public String getName() { return name; } public int getYearBorn() { return yearBorn; } public int getEducation() { return education; }

public void showData() { System.out.println("name: System.out.println("yearBorn: System.out.println("education: System.out.println(); } public void setYearBorn(int y) public void setName(String n) public void setEducation(int e)
}

" + getName()); " + getYearBorn()); " + getEducation());

///// SET (MODIFIER) METHODS ////////////////////////////////////////////////////////

{ yearBorn = y; } { name = n; } { education = e; }

// Java2409.java // Stage-9 of the Person class. // This stage attempts to create an copy with an existing object // at the parameter for the constructor of the second object. // The Person09 class is identical to the Person08 class. public class Java2409 { public static void main (String args[]) { System.out.println("Java2409.java, Person Class, Stage 9\n"); Person09 person1 = new Person09("Seymour",1975,18); person1.showData();

Person09 person2 = new Person09(person1);


person2.showData();

} }

// Java2410.java // Stage-10 of the Person class. // This stage creates a copy with an existing object // as the parameter for the constructor of the second object. // This time a "copy constructor" has been added to the Person10 class. public class Java2410 { public static void main (String args[]) { System.out.println("Java2410.java, Person Class, Stage 10\n"); Person10 person1 = new Person10("Seymour",1975,18); person1.ShowData();

Person10 person2 = new Person10(person1);


person2.ShowData(); System.out.println();

// Person10.java // Stage 10 of the Person class adds a copy constructor. // This file supports the Java2410.java executable file. public class Person10 { ///// PRIVATE PERSON ATTRIBUTES ////////////////////////////// private String name; private int yearBorn; private int education;

///// COPY CONSTRUCTOR ////////////// public Person10(Person10 p) { name = p.name; yearBorn = p.yearBorn; education = p.education; System.out.println("Copy Object Constructed\n"); }
}

Copy Constructors
public Person10(Person10 p) { System.out.println("Calling Copy Constructor"); name = p.name; yearBorn = p.yearBorn; education = p.education; }
A copy constructor is a constructor, which instantiates a new object as a copy of an existing object. A copy constructor uses a single parameter, which is an object of the same class as the copy constructor. Java has a clone method, which makes copies of existing objects. Details of the clone method will be shown in a future chapter.

// Java2411.java Stage-11 of the Person class. // This program gives the impression that the assignment operator assigns a copy from one // object to another object. In reality it makes a copy of the same object reference. public class Java2411 { public static void main (String args[]) { System.out.println("Java2411.java, Person Class, Stage 11\n"); Person11 person1 = new Person11("Seymour",1975,18); System.out.println("Person 1 Data"); person1.showData(); person1.pause(); Person11 person2 = new Person11(); System.out.println("Person 2 Data"); person2.showData(); person2.pause();

person2 = person1;

System.out.println("Person 2 Data"); person2.showData(); person2.pause(); person2.setName("Billy Bob"); person2.setYearBorn(1965); person2.setEducation(5); System.out.println("Person 2 Data"); person2.showData(); person2.pause(); System.out.println("Person 1 Data"); person1.showData(); // note that person1 is altered like person2 }

// Java2412.java // This program demonstrates that an object stores the memory address where the // object data is located. It does not store the data. When one object is assigned // to another object, the address is copied, not the data. public class Java2412 { public static void main (String args[]) { System.out.println("\nJava2412.java\n"); Person person1 = new Person(); Person person2 = new Person();

System.out.println("person1 value: " + person1); System.out.println("person2 value: " + person2); person2 = person1; System.out.println(); System.out.println("person2 value: " + person2);
System.out.println();

} } class Person { private String name; public Person() { name = "John Doe"; } }

What Is Going On? Part 1

person1 @df6ccd

person2 @601bb1

df6ccd Kathy

601bb1 Tom

What Is Going On? Part 2


person2 = person1;
person1 @df6ccd person2 @df6ccd

df6ccd Kathy

601bb1 Tom

What Is Going On? Part 3


person2.setName("George");
person1 @df6ccd person2 @df6ccd

df6ccd George

601bb1 Tom

Objects and Simple Data Types Store Information Differently


Simple (primitive) data types store assigned values directly in their allocated memory locations. Objects store memory references of the memory locations allocated during the construction of the object.

Aliasing
Aliasing occurs when two or more variables
reference the same memory location.

Any change in values referenced by one variable brings about a change in the referenced values of the other variable(s).

// Java2413.java Stage-12 of the Person class. // This program demonstrates the scope of an object. The program will only compile // with several statements commented out. Remove the comments and notice how the // program does not compile, because the objects are no longer in scope. public class Java2413 { public static void main (String args[]) { System.out.println("Java2412.java, Person Class, Stage 12\n"); System.out.println("Scope of Main"); Person12 person1 = new Person12("Kathy",1950,16); person1.showData(); person1.pause(); { System.out.println("\nScope of Main - Sub1"); Person12 person2 = new Person12("Joseph",1960,20); person2.showData(); person2.pause(); person1.showData(); person2.pause(); { System.out.println("\nScope of Main - Sub2"); Person12 person3 = new Person12("Joyce",1972,12); person3.showData(); person3.pause(); } System.out.println("\nBack in Scope of Main - Sub1"); person1.showData(); person1.pause(); person2.showData();

//

person3.showData();

} System.out.println("\nBack in Scope of Main"); person1.showData();

//
}
}

person2.showData();

// Java2414.java // This program intentionally uses identical parameter identifiers in the constructor method // as the private attribute identifiers of the Car class. This has an undesirable result. // The information, passed by parameters, does not appear to reach its intended destination. public class Java2414 { public static void main (String args[]) { System.out.println("\nJava2414.java\n"); Car ford = new Car("Explorer",2002,30000.0); ford.showData(); } } class Car { private String make; private int year; private double cost;

public Car(String make, int year, double cost) { make = make; year = year; cost = cost; }
public void showData() { System.out.println("make: " + make); System.out.println("year: " + year); System.out.println("cost: " + cost); System.out.println(); } }

// Java2415.java // The problem of the previous program is solved by using the <this> reference // to explicitly indicate the meaning of an identifier. public class Java2415 { public static void main (String args[]) { System.out.println("\nJava2415.java\n"); Car ford = new Car("Explorer",2002,30000.0); ford.showData(); } } class Car { private String make; private int year; private double cost; public Car(String make, int year, double cost) {

this.make = make; this.year = year; this.cost = cost;

} public void showData() { System.out.println("make: " + make); System.out.println("year: " + year); System.out.println("cost: " + cost); System.out.println(); } }

The this Pointer


The this pointer of an object is a pointer to the object itself. Aside from what is shown on the previous slide, its primary use is readability when dealing with multiple objects. It allows you to distinguish between this object and other objects.

// Java2416.java // This program demonstrates the use of static "class" methods that do not require // the creation of an object. public class Java2416 { public static void main(String[] args) { System.out.println("\nJava2416.java\n"); System.out.println("100 + 33 = " + Calc.add(100,33)); System.out.println("100 - 33 = " + Calc.sub(100,33)); System.out.println("100 * 33 = " + Calc.mul(100,33)); System.out.println("100 / 33 = " + Calc.div(100,33)); System.out.println(); } } class Calc { public static double add(double a, double b) public static double sub(double a, double b) public static double mul(double a, double b) public static double div(double a, double b)

{ return a + b; } { return a - b; } { return a * b; } { return a / b; }

// Java2417.java // This program uses the same Calc class as the previous program. This time an object // of the Calc class is constructed. This is possible, but neither necessary, nor desirable. public class Java2417 { public static void main(String[] args) { System.out.println("\nJava2417.java\n");

Calc c = new Calc();

System.out.println("100 + System.out.println("100 System.out.println("100 * System.out.println("100 / System.out.println(); } }

33 = " + c.add(100,33)); 33 = " + c.sub(100,33)); 33 = " + c.mul(100,33)); 33 = " + c.div(100,33));

class Calc { public static double add(double a, double b) public static double sub(double a, double b) public static double mul(double a, double b) public static double div(double a, double b) }

{ { { {

return a + b; return a - b; return a * b; return a / b;

} } } }

Class Methods
It is possible to access methods directly without first creating an object. Methods that are accessed in this manner are called Class Methods. Class methods need to be declared with the static keyword used in the heading like: public static double Add(double A, double B) { return A + B; } Accessing a class method is done with the class identifier, followed by the method identifier, like: System.out.println(Calc.Add(X,Y)); It is possible to access static methods with object identifiers. This is considered poor styling and should be avoided.

// Java2418.java // This program is an example of multiple objects using the same static class attribute. public class Java2418 { public static void main(String[] args) { System.out.println("\nJava2418.java\n"); int newScore; Game.setHS(1000); System.out.println("Starting High Score is " + Game.getHS()); System.out.println(); Game game1 = new Game("Tom"); System.out.println(game1.getName() + "'s score is " + game1.getScore() + " compared to " + game1.getHS() + " high score"); newScore = game1.getScore(); if (newScore > game1.getHS()) game1.setHS(newScore); Game game2 = new Game("Sue"); System.out.println(game2.getName() + "'s score is " + game2.getScore() + " compared to " + game2.getHS() + " high score"); newScore = game2.getScore(); if (newScore > game2.getHS()) game2.setHS(newScore); Game game3 = new Game("Lois"); System.out.println(game3.getName() + "'s score is " + game3.getScore() + " compared to + game3.getHS() + " high score"); newScore = game3.getScore(); if (newScore > game3.getHS()) game3.setHS(newScore); System.out.println("Highest score is " + game3.getHS()); System.out.println();

}
}

class Game {

private static int highScore; // highest score of any game played


private int score; private String player; public Game(String name) { player = name; playGame(); } public String getName() // current object score // name of the current player

public static int getHS()

{ return player; }

{ return highScore; }

public int getScore() { return score; } public void playGame() { score = (int) (Math.random() * 10000); }

public static void setHS(int newScore) { highScore = newScore; }


}

// Java2419.java // This program uses static attributes and static methods to store school // budget information and object attributes and object methods to store department information. public class Java2419 { public static void main(String[] args) { System.out.println("\nJava2419.java\n"); Budget.setSchoolBalance(100000); System.out.println(Budget.getSchoolBalance() + " initial school budget\n"); Budget budget1 = new Budget("English",20000); Budget budget2 = new Budget("Math",15000); Budget budget3 = new Budget("Comp Science",6000); System.out.println(); budget1.setDeptBalance(-5000); System.out.println("Deduct 5000 from English"); System.out.println(budget1.getDeptBalance() + " left in " + budget1.getDeptName()); System.out.println(Budget.getSchoolBalance() + " left in school budget\n"); System.out.println("Deduct 8000 from Math"); budget2.setDeptBalance(-8000); System.out.println(budget2.getDeptBalance() + " left in " + budget2.getDeptName()); System.out.println(Budget.getSchoolBalance() + " left in school budget\n"); System.out.println("Deduct 9000 from Comp Science"); budget3.setDeptBalance(-9000); System.out.println(budget3.getDeptBalance() + " left in " + budget3.getDeptName()); System.out.println(Budget.getSchoolBalance() + " left in school budget\n"); System.out.println(); } }

class Budget { private static int schoolBalance; private int deptBalance; private String deptName;

// money left in school budget // money left in department budget // stored department name

public Budget (String dn,int db) { deptBalance = db; deptName = dn; System.out.println("Constructing " + deptName + " object with " + db); } public static void setSchoolBalance(int amount) public static int getSchoolBalance() public void setDeptBalance(int amount) { deptBalance += amount; setSchoolBalance(amount); } public String getDeptName() public int getDeptBalance() { return deptName; } { return deptBalance; } { schoolBalance += amount; } { return schoolBalance; }

Static Methods & Static Attributes


Static methods and static attributes can be
accessed for the entire duration of a program. Static variables (attributes) can be accessed by static methods and object methods.

Instance variables (attributes) can be accessed by only object methods.

The drawLine Method


drawLine(int x1, int y1, int x2, int y2) Draws a line from coordinate (x1,y1) to coordinate (x2,y2)

x1, y1

x2, y2

// Java2420.java // This program demonstrates how to draw lines. // Lines are drawn from (X1,Y1) to (X2,Y2) with the <drawLine(X1,Y1,X2,Y2)> method. // This program uses the "application" approach. import java.awt.*; import java.awt.event.*; public class Java2420 { public static void main(String args[]) { GfxApp gfx = new GfxApp(); gfx.setSize(900,700); gfx.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}}); gfx.show(); } } class GfxApp extends Frame { public void paint(Graphics g) { g.drawLine(0,0,800,600); g.drawLine(0,600,800,0); g.drawLine(100,300,700,300); g.drawLine(400,100,400,500); } }

The Deprecated API Warning


The warning message below appears when you compile applications that use the Graphics class. The warning can be ignored.

// Java2421.java // This program demonstrates how to draw lines. // Lines are drawn from (X1,Y1) to (X2,Y2) with the // <drawLine(X1,Y1,X2,Y2)> method. // This program uses the applet approach. import java.awt.*; public class Java2421 extends java.applet.Applet { public void paint(Graphics g) { g.drawLine(0,0,800,600); g.drawLine(0,600,800,0); g.drawLine(100,300,700,300); g.drawLine(400,100,400,500); } } <!-- Java2421.html --> <APPLET CODE = "Java2421.class" WIDTH=800 HEIGHT=600> </APPLET>

// Java2422.java // This program draws a series of pixels with the <drawLine> method. // This is accomplished by using the same start and end coordinates. import java.awt.*; import java.awt.event.*; public class Java2422 { public static void main(String args[]) { GfxApp gfx = new GfxApp(); gfx.setSize(900,700); gfx.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}}); gfx.show(); } } class GfxApp extends Frame { public void paint(Graphics g) { for (int x=100, y=100; x <= 500; x+=5, y+=5) g.drawLine(x,y,x,y); } }

The drawRect Method


drawRect(int x, int y, int width, int height)
Draws a rectangle with top-left corner at coordinate (x,y) using width and height dimensions. fillRect uses identical parameters, but fills in the rectangle.

x, y
height width

// Java2423.java // This program demonstrates the rectangle command. A rectangle is drawn from the top-left (X,Y) // coordinate of a rectangle followed by Width and Height using <drawRect(X,Y,Width,Height)>. // The <fillRect> method draws a rectangle filled with default black or the currently specified color. import java.awt.*; import java.awt.event.*; public class Java2423 { public static void main(String args[]) { GfxApp gfx = new GfxApp(); gfx.setSize(900,700); gfx.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}}); gfx.show(); } } class GfxApp extends Frame { public void paint(Graphics g) { g.drawRect(50,50,100,100); g.fillRect(100,300,300,200); g.drawRect(300,100,300,150); g.fillRect(500,400,200,100); } }

The drawRoundRect Method


drawRoundRect(X,Y,Width,Height,CornerW,CornerH)
Draws a rectangle with top-left corner at coordinate (X,Y) using Width and Height dimensions. CornerW and CornerH are the Width and Height values of the rectangle that dimensions the size of the rounded corners.

fillRoundRect uses the same parameters, but fills the rounded rectangle completely.

CornerH

CornerW
The quartered oval is used to create the 4 rounded corners.

// Java2424.java // The <roundRect> method draws rectangles with rounded corners. // Two additional parameters are provided, which indicate the size of // the rounded corner. The <fillRoundRect> method floodfills rounded rectangles. import java.awt.*; import java.awt.event.*; public class Java2424 { public static void main(String args[]) { GfxApp gfx = new GfxApp(); gfx.setSize(900,700); gfx.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}}); gfx.show(); } } class GfxApp extends Frame { public void paint(Graphics g) { g.drawRoundRect(50,50,100,100,20,20); g.fillRoundRect(100,300,300,200,50,100); g.drawRoundRect(300,100,300,150,100,50); g.fillRoundRect(500,400,200,200,100,100); } }

The drawOval Method


drawOval(int x, int y, int width, int height)
Draws an oval that is circumscribed by the rectangle with top-left corner at coordinate (x,y) using width and height dimensions. fillOval uses identical parameters, but fills in the oval.

x, y
height width

// Java2425.java // This program uses the <drawOval> method to draw ovals and circles. // The four parameters of the <drawOval> method are identical to the <drawRect> // method. With <drawOval(X,Y,Width,Height)> (X,Y) is the coordinate of the // top-left corner of the rectangle that circumscribes the oval. import java.awt.*; import java.awt.event.*; public class Java2425 { public static void main(String args[]) { GfxApp gfx = new GfxApp(); gfx.setSize(900,700); gfx.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}}); gfx.show(); } } class GfxApp extends Frame { public void paint(Graphics g) { g.drawOval(50,50,100,100); g.fillOval(100,300,300,200); g.drawOval(400,50,200,300); g.fillOval(500,400,200,200); } }

The drawArc Method


drawArc(int x, int y, int width, int height, int start, int degrees)
Draws part of an oval. The 1st 4 parameters are the same as drawOval. Start indicates the degree location of the beginning of the arc. Degrees indicates the number of degrees traveled by the arc. 0 degrees is at the 3:00 oclock position and increases counter clockwise to 360 degrees. fillArc uses identical parameters, but fills in the arc.

x, y

90

180 270

0, 360

height

width

// Java2426.java // This program uses the drawArc & fillArcs methods. drawArc(X,Y,Width,Height,Start,Degrees) // uses the first four parameters in the same manner as the <drawOval> method. Start is the degree // value of the arc-start and Degrees is the number of degrees the arc travels. import java.awt.*; import java.awt.event.*; public class Java2426 { public static void main(String args[]) { GfxApp gfx = new GfxApp(); gfx.setSize(900,700); gfx.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}}); gfx.show(); } } class GfxApp extends Frame { public void paint(Graphics g) { g.drawArc(50,50,100,100,0,180); g.fillArc(200,50,100,100,0,270); g.drawArc(350,50,100,100,0,360); g.fillArc(500,50,100,100,0,-180); g.drawArc(50,250,100,200,0,180); g.fillArc(200,250,100,200,0,270); g.drawArc(350,250,200,100,0,360); g.fillArc(350,400,200,100,0,-180); } }

The setColor Method


setColor(Color.constant)
Sets the graphics display color of the following graphics output to the specified constant of the Color class. Color constants are combinations of Red, Green and Blue (RGB) values. The following constants are defined for the Color class: red green blue 255,0,0 0,255,0 0,0,255 yellow gray lightGray 255,255,0 128,128,128 192,192,192

orange
cyan magenta

255,200,0
0,255,255 255,0,255

drakGray
pink black white

64,64,64
255,175,175 0,0,0 255,255,255

// Java2427.java // This program demonstrates the pre-defined // color objects used by the <setColor> method. // The comments show the (RGB) values for each // color. import java.awt.*; import java.awt.event.*; public class Java2427 { public static void main(String args[]) { GfxApp gfx = new GfxApp(); gfx.setSize(900,700); gfx.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}}); gfx.show(); } }

class GfxApp extends Frame { public void paint(Graphics g) { g.setColor(Color.red); // 255, 0, 0 g.fillOval(20,30,80,80); g.setColor(Color.green); // 0, 255, 0 g.fillOval(120,30,80,80); g.setColor(Color.blue); // 0, 0, 255 g.fillOval(220,30,80,80); g.setColor(Color.orange); // 255, 200, 0 g.fillOval(320,30,80,80); g.setColor(Color.cyan); // 0, 255, 255 g.fillOval(20,130,80,80); g.setColor(Color.magenta); // 255, 0, 255 g.fillOval(120,130,80,80); g.setColor(Color.yellow); // 255, 255, 0 g.fillOval(220,130,80,80); g.setColor(Color.gray); // 128, 128, 128 g.fillOval(320,130,80,80); g.setColor(Color.lightGray); // 192, 192, 192 g.fillOval(20,230,80,80); g.setColor(Color.darkGray); // 64, 64, 64 g.fillOval(120,230,80,80); g.setColor(Color.pink); // 255, 175, 175 g.fillOval(220,230,80,80); g.setColor(Color.black); // 0, 0, 0 g.fillOval(320,230,80,80); } }// Color.white is also available (255, 255, 255)

// Java2428.java // This program shows all the shades of Red, Green and Blue using the // <setColor> method with new RGB parameter values. import java.awt.*; import java.awt.event.*; public class Java2428 { public static void main(String args[]) { GfxApp gfx = new GfxApp(); gfx.setSize(900,700); gfx.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}}); gfx.show(); } } class GfxApp extends Frame { public void paint(Graphics g) { for (int red = 0; red <= 255; red++) { g.setColor(new Color(red,0,0)); g.drawLine(red,0,red,600); } for (int green = 0; green <= 255; green++) { g.setColor(new Color(0,green,0)); g.drawLine(green+255,0,green+255,600); } for (int blue = 0; blue <= 255;blue++) { g.setColor(new Color(0,0,blue)); g.drawLine(blue+510,0,blue+510,600); } } }

// Java2429.java // This program draws three squares with user-defined colors. import java.awt.*; import java.awt.event.*; public class Java2429 { public static void main(String args[]) { GfxApp gfx = new GfxApp(); gfx.setSize(900,700); gfx.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}}); gfx.show(); } } class GfxApp extends Frame { Color myRed = new Color(255,0,64); Color myGreen = new Color(16,255,16); Color myBlue = new Color(64,64,255); public void paint(Graphics g) { g.setColor(myRed); g.fillRect(20,30,100,100); g.setColor(myGreen); g.fillRect(140,30,100,100); g.setColor(myBlue); g.fillRect(260,30,100,100); } }

Anonymous Objects
Situations exist where an object identifier is not necessary when creating a new object.
The majority of objects have an object identifier like these two examples: Bank tom = new Bank(2500); Color myRed = new Color(255,0,64); There are also objects that are used as parameters in a method call like: g.setColor(new Color(100,100,100)); A new Color object is created, but not identified. Such objects are called anonymous objects.

1. 2. 3. 4.

Load Paint Click [Colors] - [Edit Colors] - [Define Custom Colors] Click the triangle at the right side of the window Move the crosshairs and triangle until you get the color you want in the Color/Solid box. 5. Copy the Red, Green, and Blue numbers into your java program.

6. Ignore the Hue, Sat, and Lum!

// Java2429.java Try This! Add your customized color! import java.awt.*; import java.awt.event.*; public class Java2429 { public static void main(String args[]) { GfxApp gfx = new GfxApp(); gfx.setSize(900,700); gfx.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}}); gfx.show(); } } class GfxApp extends Frame { Color myRed = new Color(255,0,64); Color myGreen = new Color(16,255,16); Color myBlue = new Color(64,64,255);

Color myBrown = new Color(150,100,15);


public void paint(Graphics g) { g.setColor(myRed); g.fillRect(20,30,100,100); g.setColor(myGreen); g.fillRect(140,30,100,100); g.setColor(myBlue); g.fillRect(260,30,100,100); }

g.setColor(myBrown); g.fillRect(380,30,100,100);

Special Note for People Who Create Web Pages


This same technique can be used to pick colors for a web page. If you ever do a View - Source on a web page, you may see something like:

text="#ffff00" bgcolor="#cc33cc
These are hexadecimal (base 16) codes for the colors. These codes go from 00(hex) to ff(hex) for each color. The 1st 2 digits is the red value. The 2nd 2 digits is the green value. The 3rd 2 digits is the blue value.

This does assume you can convert from base 10 to base 16.

Das könnte Ihnen auch gefallen