186
________________________________________________________________________ Copyright © 2000 Robbie Kailley Java Starter: A Student Workbook for Java Internet Programming BY R.Kailley

Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Java Starter:

A Student Workbook

for Java Internet Programming

BY

R.Kailley

Page 2: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

PREFACE ii

________________________________________________________________________ Copyright © 2000 Robbie Kailley

AUTHORS Author Robbie Kailley Program Development Robbie Kailley Page Layout Robbie Kailley

Copyright © 2000 by Robbie Kailley ISBN: 0-9732175-0-2

No Part of this book may be used or reproduced in any form or by any means, or stored in a database or retrieval system, without prior written permission of the author/publisher. All rights reserved. Java is a trademark of Sun Microsystems, Inc. Microsoft DOS and Notepad are registered trademarks of Microsoft Corporation in the United States and/or other countries.

This book covers JavaTM

version 1.1.x which shares core programming

components with JavaTM

1.2 and JavaTM

2.

To order books, contact the author by email: Robbie Kailley Email Address: [email protected] Book Website: http://www3.telus.net/javastarter

PRICING (Money orders, or Certified Cheques): Java Starter Workbook $25.00 Teacher Disc including all book examples, and solutions to problems $5.00 Shipping/Handling All shipping is done through Canada Post. Please indicate your postal code in your request for books, as it is needed when using the parcel calculator for Canada Post.

ABOUT THE AUTHOR: A practicing high school computer and science teacher for over 7 years, the author has taught IT (Computer Science) 11,12 and AP computer Science. He completed his Masters Degree in Computer Science Education at UBC. He is also a sessional instructor at UBC, teaching computer studies courses in the Department of Curriculum Studies in the Faculty of Education. He has participated in several Horizons conferences by leading a hands-on seminar on Java Programming. .

Page 3: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

PREFACE iii

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Java Programming Summary Sheet

Creating Basic GUI components

mybutton=new Button(“Press me”); mytextfield=new TextField(10); mytextarea=new TextArea(5,10); mylabel=new Label(“Hello”); Setting the coordinates of components. 1)Include the line setLayout(null); in the init method. 2)mybutton.setBounds(10,10,50,50);

Summary of basic TextArea/TextField methods

Method Explanation Example

getText(); gets the current information from a textArea/Field in String form

input.getText();

setText(); puts in text into the desired area,replacing whatever was there before

input.setText(“Hello”);

append(); adds text to previously existing text in a TextArea/Field input.append(“add this”);

“\n” place a return after printed statement input.append(“Hi”+”\n”);

setEditable(); decides whether a user can change the information in a TextArea/Field

input.setEditable(true); or input.setEditable(false);

Converting Strings into numbers if num1 is an integer:

num1=Integer.valueOf(wordnumber).intValue(); if num1 is a double ( decimal number)

num1=Double.valueOf(wordnumber).doubleValue();

Basic Applet Framework import java.awt.*; Graphics screen; public void name extends java.applet.Applet { public void init() { } public void paint(Graphics screen) { } } //ends class

Basic Graphics methods screen.drawRect(10,10,50,50); //x,y,width,height screen.drawRoundRect(10,10,50,50,5,5);//draws a rounded rectangle with corners based on oval width of 5,height 5. screen.fillOval(10,10,50,50);//fills the shape with the current color screen.drawLine(20,20,50,50); //connects the 2 points screen.drawArc(10,10,50,50,0,180); //last 2 numbers are starting angle and sweep of arc. screen.setColor(Color.red); //colors are red, black,blue,cyan,gray,darkGray,lightGray,green,magenta,orange,pink,red,white,yellow mypoly=new Polygon(); mypoly.addPoint(10,10); screen.fillPolygon(mypoly);

Variable Types

Data Type Description Example int a whole number,values from -2 billion to 2 billion 10, -10 long a whole number values from -9E18 to 9E18 3,000,000,000,000 double a decimal number from -1.7E308 to 1.7E308 102.998E48 char a single character ,must be in single quotes ‘r’ String a combination of characters, must be enclosed in quotes “Henry” boolean value can either be true or false the value is either true or false Casting num1=(int) (9/2); //this will force the decimal result of 9/2 to become an integer, it is rounded

Page 4: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

PREFACE iv

________________________________________________________________________ Copyright © 2000 Robbie Kailley

VARIOUS IF THEN STATEMENT STRUCTURES

For Loops

Operator Meaning Example

== equals to if (num1==num2) {

!= not equal to if (num1!=num2) {

< less than if (grade<90) {

<= less than or equal to if (salary<=40000) {

> greater than if (SAT>1100) {

>= greater than or equal to if (GPA>=3.5) {

Operator Meaning Example

&& and if (GPA>3.5 && SAT>1200) {

|| or if (GPA>3.5 || SAT>1200) {

if (condition is true) instruction1; else instruction2;

if (condition is true) { instruction1; instruction2; } else if(condition2 is true) { instruction3; instruction4; }

if (condition is true) { instruction1; instruction2; } else { instruction3; instruction4; }

if (condition is true) { instructions; instructions; }

Type1 Type2

Type 4Type3

for (int counter=0;counter<10;counter=counter+1) { output.setText(“This is still looping”); }//ends for loop

card=1; do { output.setText(“You have”+card+”total cards”); card=card+1;

} while (card<10);

cards=1; while (cards<10) { dealcard(); cards=cards+1;

}

While Loops Do While Loops

Relational Operators

Logical Operators

Page 5: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

PREFACE v

________________________________________________________________________ Copyright © 2000 Robbie Kailley

WHO THIS BOOK IS FOR: High School Students If you are taking an introductory course in computer science or Information Technology 10,11 or 12, this book will help you learn the basics of programming and even some multimedia programming. These are some core components of the high school curriculum in many areas in North America. You will be able to use this book to help you learn at home and catch up on material if you miss class, or even work ahead if you want! Adult learners This book is meant for anyone who wants to learn Java programming basics, using the newest version of Java. It assumes you have no previous knowledge of programming and starts right from the beginning. If you want to learn how to program, and want to do it using the Java language, then this book is for you. Teachers As teachers of computer courses, we face the daunting task of constantly learning new things quickly and then teaching the students these concepts. This book will teach you the basics of programming in Java so you can begin teaching your students this exciting new language as quickly as possible. You can even use this book as a textbook for a course. How this book is organized: This book provides an organized, structured approach to Java programming that is created by a high school computer science teacher (including AP computer science) who has over five years of teaching experience. Because this book is created by a teacher, it is organized and written with an understanding of how learning takes place. This book

teaches by example, and provides many visual diagrams to help students understand the concepts. This book provides mastery questions at the end of each sub-section so students can get instant feedback on a topic being learned. There are larger programming questions at the end of every chapter. A disk is provided (if you purchase the teacher edition) with all the answers to every problem in the book. The disk also contains all the examples contained within the book.

Page 6: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

PREFACE vi

________________________________________________________________________ Copyright © 2000 Robbie Kailley

WHY JAVA? There are many reasons to learn Java or any programming language. Technology is expanding at exponential rates, and with its improved capabilities, we have created an industry that has made an impact in every aspect of our lives, from banking to home entertainment. Regardless of what particular aspect of technology you want to specialize in, learning a programming language will enable you to participate in this new industry. Perhaps this book will be the first step that you take in obtaining your degree or certificate in programming! What Java provides:

• an fun, gentle introduction to programming if it is your first programming language

• programs which can quickly be displayed on the internet, making anyone a publisher immediately

• an introduction to an industry standard language, which is being used by major technology companies to create software

• the syntax (or words used by the Java programming language) is quite similar to C++, which is another industry standard language. Therefore, by learning Java, transferring the knowledge to learn C++ should be made easier.

• opportunities to learn core aspects of programming that are transferable to any programming language in existence.

Page 7: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

PREFACE vii

________________________________________________________________________ Copyright © 2000 Robbie Kailley

TABLE OF CONTENTS

WHO THIS BOOK IS FOR: ................................................................V

WHY JAVA?....................................................................................VI

TABLE OF CONTENTS ................................................................... VII

TABLE OF CONTENTS- TABLES ......................................................XI

TABLE OF CONTENTS-PROGRAMMING EXAMPLES .................... XII

UNIT 1:STARTING JAVA ................................................................. 1

Unit Overview................................................................................................................ 1 1.1 What is Java? ........................................................................................................ 1 1.2 What is a programming language? ....................................................................... 1 1.3 What do You need to Run Java?........................................................................... 3 1.4 Getting the Java Developers kit (JDK) for the PC from the Internet........... Error!

Bookmark not defined. 1.5 Setting up Java on your computer once you downloaded the jdk................ Error!

Bookmark not defined. 1.6 Setting up JDK on the Macintosh ..................................................................... 166

UNIT EXERCISES............................................................................................................. 3

UNIT 2- YOUR FIRST APPLET ........................................................ 5

Unit Overview................................................................................................................ 5 2.1 What is an applet?................................................................................................. 5 2.2 Outline of Basic steps to run a java program on a PC .......................................... 5 2.3 Some Naming and Saving Tips........................................................................... 11 2.4 Running an applet on the macintosh................................................................... 11

Unit Exercises .............................................................................................................. 12

UNIT 3- BASIC APPLET CREATION .............................................. 15

Unit Overview.............................................................................................................. 15 3.1 Basic Applet Framework .................................................................................... 15 3.2 Your Second Applet with the paint method explained ....................................... 18 3.3 Rules for Naming in Java.................................................................................... 19 3.4 What does the word class mean in Java? ............................................................ 19

Unit Exercises .............................................................................................................. 20

UNIT 4 - GRAPHICS ....................................................................... 21

Unit Overview.............................................................................................................. 21 4.1 Introduction to the Graphics class....................................................................... 21 4.2 The Java Coordinate System: An Introduction................................................... 22 4.3 Basic Methods of the Graphics Class:Creating Lines, Rectangles, Ovals, Arcs 23 4.4 Using the fill method .......................................................................................... 27 4.5 Using Colors ....................................................................................................... 27

Page 8: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

PREFACE viii

________________________________________________________________________ Copyright © 2000 Robbie Kailley

4.6 Creating Polygons............................................................................................... 29 4.7 drawString and Changing Fonts.......................................................................... 30 4.8 Creating your own methods and calling them from the paint method................ 31

Unit Exercises .............................................................................................................. 33

UNIT 5 VARIABLES ....................................................................... 35

Unit Overview.............................................................................................................. 35 5.1 What is a variable?.............................................................................................. 35 5.2 Declaring Variables, and the Assignment Statement.......................................... 35 5.3 Java Variable Types............................................................................................ 38 5.4 Constants............................................................................................................. 40 5.5 Java Math Functions ........................................................................................... 40 5.6 Casting ............................................................................................................... 42

Unit 5 Exercises ........................................................................................................... 43

UNIT 6-GRAPHICAL USER INTERFACE I-OUTPUT COMPONENTS

........................................................................................................ 45

Unit Overview.............................................................................................................. 45 6.1 What is a Graphical User Interface, what is a component? ................................ 45 6.2 The Basic Steps for Creating Components in your program .............................. 45 6.3 Basic TextField and TextArea methods-Obtaining and Displaying Information................................................................................................................................... 48 6.4 Converting TextField information into Numbers for Calculations and Outputting the Results................................................................................................................. 51

Unit Exercises .............................................................................................................. 53

UNIT 7 GRAPHICAL USER INTERFACE- BASIC INPUT AND EVENT

HANDLING ..................................................................................... 55

Unit Overview.............................................................................................................. 55 7.1 What is Event Handling ...................................................................................... 55 7.2 Basic Steps in Event Handling............................................................................ 55 7.3 Using the actionPerformed method to store instructions.................................... 58 7.4 Using repaint() method to recall the paint method; and the update() method .... 60

Unit Exercises .............................................................................................................. 63

UNIT 8 DECISION STATEMENTS................................................... 65

Unit Overview.............................................................................................................. 65 8.1 What is a decision statement and why do we need them? .................................. 65 8.2 Basic If..then decision statement ........................................................................ 65 8.3 Evaluating Conditions -Relational Operators ..................................................... 67 8.4 Evaluating Multiple Conditions -Logical Operators........................................... 68 8.5 Various If..then statements with examples ......................................................... 70 8.6 Checking String Equality.................................................................................... 73 8.7 An alternative decision structure: the switch statement...................................... 74

Unit Exercises .............................................................................................................. 76

Page 9: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

PREFACE ix

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 9 GUI COMPONENTS:DROP

MENUS,CHECKBOXES,SCROLLBARS........................................... 77

Unit Overview.............................................................................................................. 77 9.1 Declaring and Using Drop Menus ...................................................................... 77 9.2 Declaring and Using CheckBoxes ...................................................................... 79 9.3 Declaring and Using Checkbox groups .............................................................. 80 9.4 Declaring and Using Scrollbars .......................................................................... 82

Unit Exercises .............................................................................................................. 84

UNIT 10- LOOPS ............................................................................ 85

Unit Overview.............................................................................................................. 85 10.1 What are loops and why use them?................................................................... 85 10.2 For loops ........................................................................................................... 85 10.3 Simple Animation using For Loops.................................................................. 87 10.4 While Loops...................................................................................................... 89 10.5 Do while loops: ................................................................................................. 91 Section 10.6 Creating Random Numbers.................................................................. 92

Unit Exercises .............................................................................................................. 94

UNIT 11 IMPORTING IMAGES AND SOUNDS ................................ 95

Unit Overview.............................................................................................................. 95 11.1 How pictures are used in Java........................................................................... 95 11.2 Basic Steps in using images in your program................................................... 95 11.3 How sounds are used in Java ............................................................................ 96 11.4 Basic Steps in using sounds in your program ................................................... 96

Unit Exercises .............................................................................................................. 97

UNIT 12 MOUSE EVENTS .............................................................. 99

Unit Overview.............................................................................................................. 99 12.1 What is a mouse event?..................................................................................... 99 12.2 Basic Steps in handling mouse events in an applet........................................... 99 12.3 Drag and Drop Example ................................................................................ 100 12.4 A simple doodle pad program example .......................................................... 106

Unit Exercises ............................................................................................................ 107

UNIT 13 KEYBOARD EVENTS ..................................................... 109

Unit Overview............................................................................................................ 109 13.1 What is a keyboard event? .............................................................................. 109 13.2 Basic steps in declaring and using keyboard events ....................................... 109 13.3 Common Key Codes ....................................................................................... 113

Unit Exercises ............................................................................................................ 113

UNIT 14:OBJECT ORIENTED PROGRAMMING .......................... 115

Unit Overview............................................................................................................ 115 14.1 What is Object Oriented Programming (OOP)? ............................................. 115 14.2 Advantages of OOP. ....................................................................................... 116 14.3 basic overview of how to create oop programs .............................................. 116

Page 10: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

PREFACE x

________________________________________________________________________ Copyright © 2000 Robbie Kailley

14.4 What is a modifier?......................................................................................... 117 14.5 Basic class construction .................................................................................. 118 14.6 Adding methods to your class......................................................................... 119 14.7 Creating the main applet program which uses the car.java class.................... 121 14.8 Final word on basic OOP................................................................................ 124 14.9 Creating a class file within the main Applet code (Optional)......................... 124

Unit Exercises:........................................................................................................... 125

UNIT 15:OBJECT ORIENTED PROGRAMMING II:ADVANCED

OBJECT CONSTRUCTION:........................................................... 127

Unit Overview: .......................................................................................................... 127 15.1 Encapsulation.................................................................................................. 127 15.2 Polymorphism................................................................................................. 128 15.3 Inheritance....................................................................................................... 130 15.4 Some notes and tips when using inheritance .................................................. 134 15.5 Final thoughts about the introduction to OOP ................................................ 135

Unit Exercises ............................................................................................................ 135

UNIT 16: THREADS AND ANIMATION ....................................... 137

Unit Objectives:......................................................................................................... 137 16.1 What is a thread?............................................................................................. 137 16.2 How to create Threads in your program to create animation.......................... 137 16.3 Reducing Flicker............................................................................................. 141 16.4 Using MediaTracker to effectively load images for animation ...................... 143

Unit Exercises:........................................................................................................... 147

UNIT 17: ARRAYS....................................................................... 149

Unit Overview............................................................................................................ 149 17.1 What is an array? ............................................................................................ 149 17.2 How to create a simple array .......................................................................... 149 Section 17.3 Using arrays and graphics .................................................................. 154 17.4 Using arrays with objects................................................................................ 156

Unit Exercises ............................................................................................................ 157

INTERLUDE-CREATING METHODS.............................................. 159

Unit Overview............................................................................................................ 159 Creating methods to accept variables ..................................................................... 159 Creating methods which return a value .................................................................. 161

Unit Exercises ............................................................................................................ 162

APPENDIX A-RESERVED WORDS................................................ 163

A.1 List of common reserved words....................................................................... 163

APPENDIX B-SETTING UP JCREATOR AND JAVA ON YOUR PC165

ITEM #1 : Getting and installing the JDK SDK.................................................... 165 ITEM #2 Getting a free java editor to type your programs in ............................. 165 Using Jcreator™ ....................................................................................................... 167

Page 11: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

PREFACE xi

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Opening Example Files from Solutions Disk Using Jcreator................................ 171

Page 12: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

PREFACE xii

________________________________________________________________________ Copyright © 2000 Robbie Kailley

TABLE OF CONTENTS- TABLES

Table 4.1 Basic steps in drawing in an applet .............................................................. 21

Table 4.6 Steps in using Polygons.................................................................................. 29

Table 5.3-Table of Variables.......................................................................................... 38

Table 5.5 Math Operators.............................................................................................. 40

Table 6.2 Declaring and using components in applets ................................................ 46

Table 6.3 Summary of basic TextArea/TextField methods......................................... 48

Table 6.4 Converting Strings into numbers ................................................................. 51

Table 8.3 Relational Operators...................................................................................... 68

Table 8.4 Logical Operators........................................................................................... 68

Table 9.1 Steps in Creating Menubars.......................................................................... 77

Table 9.2 Steps in Creating ChekBoxes ........................................................................ 79

Table 9.3 Steps in using Checkboxgroups .................................................................... 81

Table 9.4 Using ScrollBars ............................................................................................. 82

Table 10.6 Creating Random Numbers ........................................................................ 93

Table 11.2 Basic Steps in Using Images in your program........................................... 95

Table 11.4 Using sounds in your program.................................................................... 96

Table 12.2 Using Mouse Events in your Program ....................................................... 99

Table 12.3a Steps involved in drag and drop ............................................................. 101

Table 12.3b Steps in drag/drop with an image........................................................... 104

Table 13.2 Using keyboard events in an applet.......................................................... 109

Table 13.3 Common Key Codes................................................................................... 113

Table 14.1 OOP Definitions ......................................................................................... 115

Table 14.4 Modifiers ..................................................................................................... 117

Table 15.4 Preventing subclassing............................................................................... 134

Table 16.2 Using threads in applets to create animation .......................................... 138

Table 16.3 Creating an offscreen image in applets to reduce flicker ....................... 142

Table 16.4 Using MediaTracker in image animations............................................... 143

Table 10.2a Steps in creating method that accept variables ..................................... 159

Table 10.2bCreating method which return a value ................................................... 161

Page 13: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

PREFACE xiii

________________________________________________________________________ Copyright © 2000 Robbie Kailley

TABLE OF CONTENTS-PROGRAMMING EXAMPLES

Example 2.2a Hello World Applet................................................................................... 6

Example 2.2b Simple Web Page ..................................................................................... 9

Example 3.1a Import lines and program heading line ................................................ 15

Example 3.1b: Method Structure. ................................................................................. 17

Example 3.1c Basic applet framework with comments ............................................... 17

Example 3.2 A simple Graphics Applet with 2 Rectangles ......................................... 18

Example 4.1 A simple Graphics applet illustrating all the basic steps above ........... 21

Web page code for example4.1 ...................................................................................... 22

Example 4.3 Basic Shapes ............................................................................................. 26

Web Page Code for example 4.3 .................................................................................... 26

Example 4.5 Basic Java Colors ...................................................................................... 27

Example 4.5b - Using Your own colors......................................................................... 28

Example 4.6 Polygons .................................................................................................... 29

Example 4.7 drawString and Font changes................................................................. 30

Example 4.8 Using Methods in a program ................................................................... 32

Example 5.2 Simple Variable Declaration and Use in drawString ............................ 37

Example 5.3 Using and printing all the variable types................................................ 39

Example 5.4 using a constant......................................................................................... 40

Example 5.5 Using Basic Math operations ................................................................... 41

Example 5.6 Casting ....................................................................................................... 42

Example 6.2 Adding the basic components to your display........................................ 47

Example 6.3 Basic TextArea/TextField Methods......................................................... 50

Example 6.4 Converting String to Numbers and Performing Math operation ........ 52

Example 7.2 Basic Structure of Event Handling ......................................................... 57

Example 7.3 full example of input and output using events ....................................... 58

Example 7.3a Displaying button labels using actionevents......................................... 59

Example 7.4a Using repaint to draw a square in different spots ............................... 61

Example 7.4b Using our own update to stop screen from clearing between redraws

........................................................................................................................................... 62

Example 8.2 A simple if..then statement....................................................................... 66

Page 14: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

PREFACE xiv

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Example 8.2a Using a simple if..then else to determine which of 2 buttons is pressed

........................................................................................................................................... 67

Example 8.4 Using Relational and Logical operator && (and) ................................. 69

Example 8.5 Nested If..then Statement ......................................................................... 72

Example 8.6 Using Strings in Conditions ..................................................................... 73

Example 8.7 Using a Switch Statement......................................................................... 75

Example 9.1 Creating a simple drop down menu ........................................................ 78

Example 9.2 Simple CheckBox Example ...................................................................... 80

Example 9.3 Using CheckboxGroup ............................................................................. 81

Example 9.4 Simple ScrollBar Example ....................................................................... 83

Example 9.4b Scrollbars and Buttons in an applet, with listeners on both............... 83

Example 10.2a Simple For Loop with a method call in init() method ....................... 86

Example 10.2b Math Example using a For Loop......................................................... 87

Example 10.3a Animation By drawing object same as background color ................ 88

Example 10.3b Animation by redrawing the whole background............................... 89

Example 10.4a Using a simple while Loop.................................................................... 90

Example 10.4b Using a large while loop for animation............................................... 91

Example 10.5 A Do while loop ....................................................................................... 92

Example 10.6a Random Number Generation as Integers........................................... 93

Example 10.6b Random Number Generation as Decimals......................................... 94

Example 11.2 Showing a Picture on an Applet ............................................................ 96

Example 11.4 Using the loop() method to play a sound .............................................. 97

Example 12.2 Basic Mouse Handling Applet ............................................................. 100

Example 12.3a Simple Drag and Drop (Horizontal).................................................. 102

Example 12.3b Advanced Drag and Drop (Horizontal) ............................................ 103

Example 12.3c Drag and Drop with Images (Horizontal)......................................... 105

Example 12.4 A simple doodle pad example using mouse events............................. 106

Example 13.2a Basic Key Event Example. Prints out key codes ............................. 110

Example 13.2b Using Key Events in a Graphical Applet.......................................... 111

Example 13.2c Using Key Events to Move an Image................................................. 112

example car.java The complete code for car.java..................................................... 120

example 14.7 the complete version combining all the above steps ........................... 123

example 14.9 Combining class and main applet code................................................ 124

Page 15: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

PREFACE xv

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Example car.java This is the class file which uses polymorphism in its constructor

and getcolor method ..................................................................................................... 129

example 15.2 Main applet code which uses the car class defined above.................. 130

vehicle code. This is code is just a definition of a vehicle. It will be subclassed in the

next 2 programs called a_car and a_truck. ................................................................ 131

a_car code. This is a subclass of vehicle (Notice use of super( ) method) .............. 132

A_truck code. A class file that is a subclass of vehicle.Shows Overridding ........... 133

Example 15.3 The main applet code which uses a_car and a_truck........................ 134

Example 16.2 Simple animation using threads .......................................................... 139

Example 16.2b Using resume and suspend in an animation applet ......................... 140

Example 16.3 Double-Buffering example ................................................................... 142

Example 16.4 Using MediaTracker to load images in an animation ....................... 144

Example 16.4b Animation using OOP concepts with images ................................... 145

Example 17.2a Declaring and using simple arrays. ................................................... 152

Example 17.2b Letting user enter in values into an array ........................................ 153

Example 17.3 Using an Image array ........................................................................... 154

Example inter1 Sending variables to methods ........................................................... 160

Example inter2 Sending different variable types to a method ................................. 160

Example inter3 Using methods with return types ..................................................... 162

Page 16: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 1-STARTING JAVA 1

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 1:STARTING JAVA

UNIT OVERVIEW

• 1.1 What is Java?

• 1.2 What is a programming language?

• 1.3 What do you need to run Java?

• 1.4 Getting the Java Developers Kit (JDK) for the PC from the internet

• 1.5 Setting up Java on your computer once you downloaded the JDK

• 1.6 Setting up JDK on the Macintosh

1.1 WHAT IS JAVA?

Java is a new programming language for the Internet. It has many advantages that make it popular for programmers. 1) It is cross platform (it can be run on IBM’s, PC’s, Macintosh, Unix etc..) 2) It is completely object-oriented (a very organized method of programming)

3) Its programs can be viewed directly through a web page, making everyone an instant author and software developer.

4) It is a compact language that makes learning other languages like C++ easier 5) It is continually growing and because of its portability, you can share your

programming code with others. As well, you can find pre-made programming code that you can use, which can save you lots of time.

1.2 What is a programming language?

Any computer game or program such as a word processor that you may use is created from a programming language. Computer companies hire programmers to create computer programs that people buy and use. The inner working of a computer is quite complicated and requires another course just to introduce the basic topics. In this book, we will focus on how to use a programming language to make the computer do certain things. Some basic definitions you will need to understand are:

• software: this is a program that your computer runs. Examples of software are games, word processors, spreadsheets or internet browsers (Netscape or Internet Explorer)

• hardware: this is the physical equipment that makes up the computer. All the wires, the disk drives the monitor, the mouse and the keyboard. The computer hardware is what runs the computer software.

• Programming code: these are the special words that a programmer types in to communicate to the computer hardware, telling it what to do. Software is created through programming code.

A company creates a programming language. A person enters in instructions using the

special words of the programming language. The programming language is then

Page 17: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 1-STARTING JAVA 2

________________________________________________________________________ Copyright © 2000 Robbie Kailley

converted into the computers native language, which is all 0’s and 1’s (called binary code). Professional computer engineers create compilers to help convert what you have written into a language that the computer understands. The computer doesn’t really understand English words; it only understands a special language called machine language. The compiler is a special program that helps to translate your java code into machine language, so when you look at your program on a web site, the website will run it properly.

The reason why we use compilers is because the computer’s native language is very complex and the learning curve is very steep. It is much more convenient to program in English words and let the compiler do all the translating for you. Companies keep making compilers that recognize and translate different words and symbols, which has resulted in so many languages being developed for use. Some common languages are Java, Visual Basic, C++, Delphi and Pascal.

When compiling, syntax errors will be pointed out and must be corrected. After a successful compile, you can execute the program. If the program runs but not the way you want it to, you have logical errors in your code, and you must go through and correct them.

SUMMARY OF HOW LANGUAGES WORK

Code is typed into text editor Compiler translates code into language the computer understands(machine language) Then you can execute the instructions after successful compile

STEPS IN RUNNING PROGRAM

HOW JAVA RUNS

Step 1

Type in Code in a Text Editor

-You must follow proper rules of language

Step 2

Compile the program

software translates your typed code

into a language the computer understands

Step 3

Run Program (if compile is successful)

This is when the prorgram instructions

are executed.

How a Programming Language Works

General Format

Running Java

Step 1

You code is typed into an editor

Step 2

Code is compiled into BYTECODE

Bytecode is a universal language

understood by all web broswers

Step 3

If compile is successful

run program(applet) in web browser

or in given software with JDK

Page 18: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 1-STARTING JAVA 3

________________________________________________________________________ Copyright © 2000 Robbie Kailley

JAVA SPECIFICS The language the compilers translates into is called bytecode and this is universally understood by all web browsers. (Java creates the bytecode file as a .class file) All web browsers have a JVM (Java virtual machine) which the the software that helps the web browser execute the bytecode. CONCLUSION

There are some special things included with each programming language, which help a programmer type in the instructions.

• A compiler- this is the converter that takes in the words of the programming language you are using, and converts it into the language your computer can understand.

• An IDE (Integrated Development Environment)- this is the software included with the programming language. It usually included a special word processor where you can type in your programming code, and the compiler.

The basic process of creating software through a programming language is: 1. Find a problem that can be solved using a computer language 2. Create the code 3. Compile and correct the code for errors (called debugging) 4. Repeat step 3 over and over until the end product solves the problem

There are many computer languages in existence today. Each company that created the programming language tries to implement new capabilities in the language so more people will use it to create games and other applications.

1.3 What do You need to Run Java?

Our journey into programming will first require us to download the Java compiler. The version of Java we will be using throughout this book is 1.4.x since this version is the one available for the Mac and IBM. To have your system ready to run Java, you must have the following:

• a java compiler

• a text editor

• a web browser (to view the java program), or a program called an applet viewer that comes with the Java program when you download it

The complete installation instructions for PC’s and Mac’s are found in appendix B. Go there now, to install Java and then you can go onto unit 2.

UNIT EXERCISES 1)Go to the internet or use your teacher’s source, download the JDK for your computer. 2)On the Internet, go to some sites where Java applets are being used. One place is http://www.javaworld.com Find and list 3 sites, which are of educational interest that use Java applets. Describe why they are useful. 3) Use the Internet and the information in this chapter to define:

Page 19: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 1-STARTING JAVA 4

________________________________________________________________________ Copyright © 2000 Robbie Kailley

• software

• hardware

• compiler 4) What are the three things you absolutely must have to run Java? 5) What is a programming language and how does it work?

Page 20: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 2-YOUR FIRST APPLET 5

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 2- YOUR FIRST APPLET

UNIT OVERVIEW

• 2.1 What is an applet?

• 2.2 Outline of Basic steps to run a java program on a PC

• 2.3 Some Naming and Saving Tips

• 2.4 Running an applet on the macintosh

2.1 WHAT IS AN APPLET?

An applet is simply a program which is typed in java, that someone can use or play with over the Internet. An applet can be a game you make, an online calculator or anything else created in java that can be used on the Internet.

When you are typing in your java applet, what you are doing is using special words and symbols. When placed in the correct order, the words will make the computer react and do things you want it to do. This happens because when you type in a program, you compile it so the computer understands your instructions. (See unit 1 for explanation of compilers)

2.2 OUTLINE OF BASIC STEPS TO RUN A JAVA PROGRAM ON A PC

To create and run an applet you must follow these steps:

• Step 1-Create a folder to hold your java programs (in the c:)

• Step 2-type in and save your java program in a text editor

• Step 3-compiling the applet

• Step 4-Creating a web page to display the applet

• Step 5-Viewing your applet **Note:If you followed appendix B to install JCreator, type the code in from the

example in this section, but follow the steps in the appendix B to compile and view

applets using JCreator.

STEP 1-CREATE A FOLDER TO HOLD YOUR JAVA PROGRAMS (IN THE C:) Create a folder called programs in your c: drive. You should save java programs

inside here (create other folders inside of this when doing different units). Try to make the names of your folders less than 8 characters to make it easier to navigate to when you are working in DOS (in step 3). STEP 2-TYPE IN AND SAVE YOUR JAVA PROGRAM IN A TEXT EDITOR

NOTE: Make sure you ALWAYS save your java program and the web page (see section 1.6) in the same folder. (Sometimes creating separate folders for each program and its web page make finding programs easier).

a) Go to the start menu, and follow the path below.

Menu Path Start menu>>programs>>accessories>>notepad

Page 21: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 2-YOUR FIRST APPLET 6

________________________________________________________________________ Copyright © 2000 Robbie Kailley

b) In notepad type in the code from example 2.2a Type the program exactly as it is written. Java is case sensitive which means you cannot mix capitals with small letters. The Java compiler will not recognize a capital as the same as a small letter. So if a special command word such as public is written, Java will recognize it. However, if the word is typed in as Public (a capital P) Java will not recognize it. Java views them as separate words. You should type in what text is inside the box. EXAMPLE 2.2A HELLO WORLD APPLET Applet will display a message on the applet display

import java.awt.*;

public class HelloWorld extends java.applet.Applet {

public void init() {

}

public void paint(Graphics screen) {

screen.drawString("Hello World",50,50);

}

}

c) Saving your program code ****Make sure you choose the save option as *.* all file***** Save this program as HelloWorld.java

Java is CASE-SENSITIVE so you must save your program using the exact spelling of your program name.

Page 22: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 2-YOUR FIRST APPLET 7

________________________________________________________________________ Copyright © 2000 Robbie Kailley

STEP 3-COMPILING THE APPLET Go to the start menu and open up the DOS prompt.

Menu Path Windows 95,98,ME

Start>>Programs>>MS DOS Prompt

Windows 2000,NT, XP

Start>>Programs>>accessories>>Command Prompt

This will open up a DOS window or command prompt line in windows 2000 et al.. In the DOS window,navigate to the directory where your java code is. To do this, type the following lines: (you will be typing in the bold words)

c:\windows>cd.. c:\cd programs

Here is what it looks like on the win 95 computer.(Depending on your computer, your

prompts may not have the same names, in that case just use cd.. to get to the base directory and then use the cd command to navigate to the directory you created)

Then you must type in the built in java command which will compile your program. The program that follows the command word javac is compiled.

c:\programs>javac HelloWorld.java

this tells the computer to compile HelloWorld.java

Page 23: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 2-YOUR FIRST APPLET 8

________________________________________________________________________ Copyright © 2000 Robbie Kailley

If after you type in the javac line, the next line is

c:\programs>

This means the program has compiled successfully. You can now go on to the next step. If there were several lines of words and sentences when you compiled, this means there was an error in your program. Read the sentences, they will give you a clue as to what line or lines contained the errors. Go back and try to fix the lines in notepad, save the file again and compile it again. There are too many kinds of errors to list here, however, some are more common that others. Many times it is a spelling mistake, a wrong type or missing a symbol or bracket, or the words are not in the proper order. Here is what the compiling sequence will look like if it's successful.

When a java program is compiled, the computer creates a new file with the same program name but the ending is now .class. For example, the HelloWorld.java that you saved will create a new file called HelloWorld.class when it’s compiled correctly. The class file is a separate file that contains the proper translated symbols of your java code so your web browser can run your program. Whenever you want to make changes to your program, you always open up the HelloWorld.java program which contains your writing. The HelloWorld.class is just for the web browser and it is written is a special language called bytecode. Bytecode is what makes java cross platform because any machine’s web browser, whether it be a Macintosh or a PC will recognize bytecode.

Since there was nothing that was written after the javac line and the next line was just a regular DOS line, this means the program compiled successfully. You can go onto the next step.

Page 24: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 2-YOUR FIRST APPLET 9

________________________________________________________________________ Copyright © 2000 Robbie Kailley

NOTE: After you make a change to your code, you have to recompile the corrected code before trying to view your applet. This makes sure the “class” code which is created is the most current one.

STEP 4-CREATING A WEB PAGE TO DISPLAY THE APPLET

Creating complex web pages is an enormous topic which will be dealt with in another booklet. To create a simple web page that contains your java applet requires you to do the following.

• Go to notepad again [Start>>Programs>>Accessories>>Notepad]

• Open a new file.

• Type in the following, exactly as its written

EXAMPLE 2.2B SIMPLE WEB PAGE

<html> <applet code="HelloWorld.class" height=”300” width=”300”> </applet> </html>

• save the file as HelloWorld.html (you can actually use any name, as long as it ends with extension .html) MAKE SURE YOU SAVE THE FILE AS

All Files *.* (see step #2 for more information)

• NOTICE the applet code=”HelloWorld.class” . This means the applet is referring to the class code that was created by the compiler.

NOTE: For future reference, all you need to do is copy this web page code again, and replace the HelloWorld.class with the name of your applet that you want to see. Also, don’t be afraid to play around with the width and the height.

STEP 5-VIEWING YOUR APPLET You have 2 options of how you want to view your applet Option #1: Use a web browser to view the applet Option #2: Use the built in appletviewer included with the JDK to look at the applet Option #1 Web Browser:

All web browsers are a little different from one another. Usually in the File menu, there is an item called open file or open local. Choose that menu item and it should let you navigate through your computer to your web page file created in step #4. Select the

indicates that it’s a web page

The numbers for height and width are in pixels, which is a unit used to describe space on a display screen. Most typical displays have a 800x600 display area. However, many people adjust their display areas, check with your instructor if you are not sure of your monitors display area.

Page 25: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 2-YOUR FIRST APPLET 10

________________________________________________________________________ Copyright © 2000 Robbie Kailley

web page file, and the Internet browser should open up with the applet showing (look on the next page for a picture of what the applet looks like). Option #2 Applet Viewer Open the MS-DOS Prompt using the following menu path:

Menu Path Windows 95,98,ME

Start>>Programs>>MS DOS Prompt

Windows 2000,NT, XP

Start>>Programs>>accessories>>Command Prompt

Once the DOS window is open, navigate to the folder where your web page and java code is located. Then call up the appletviewer and give it the web page it’s supposed to open. In this case that would involve you completing the following lines. (You fill in the bold faced parts)

c:\WINDOWS>cd.. c:\>cd programs c:\programs>appletviewer HelloWorld.html

The applet should look like this:

calls up the built in applet viewer this tells the appletviewer

what web page to load up.

Page 26: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 2-YOUR FIRST APPLET 11

________________________________________________________________________ Copyright © 2000 Robbie Kailley

2.3 SOME NAMING AND SAVING TIPS

NOTE: When you are saving your program, you must save it using the following format: your_program_name.java your_program_name is the title of your program, which is the line of the program which reads: public class ____________ extends java.applet.Applet { All of your programs will have the above line and you may choose your own program names. There are a few restrictions in naming programs that we will cover in the next unit.

In the example above, the program name is HelloWorld. So, you would save the document as HelloWorld.java

2.4 RUNNING AN APPLET ON THE MACINTOSH

If you are using a Macintosh, type in the same program as described in section 2.2

example 2.2a into a texteditor (such as SimpleText or BBEdit).

To compile the program, drag the icon for your program code, onto the javac icon (located in the MRJ folder, if you can’t find it, use the find function). Use the results of the compile to check for errors or if there are no errors it will be indicated in the textbox after the compiler is finished.

After having a successful compile, create a web page (follow section2.2 step 4). Either 1)Drag this icon on the applet applet runner icon. or 2.)Open your local web page on a web browser.

program name goes here

Page 27: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 2-YOUR FIRST APPLET 12

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT EXERCISES

1.Fill in the blanks a) A __________ is created by computer engineers to help convert programming code into a language the computer can understand. b) To view your applet you must use either a ___________________ or an __________________. c) The name of your code should always have the extension ________________. d)The name of your saved file should be the same as the name of your __________________. e) Because Java differentiates between lower-case and capital letters, we say that java is a _____________ - ______________ language. 2.Short Answer Questions: a)What is an applet? b)What are some common types of compiler errors? c)Are you allowed to pick your own program name, if so where in all Java programs does the program name go? 3.Programming Projects: a)Change the applet height to 500 and the width to 500, view the applet again with these new dimensions b)Change the message in the applet to “The journey of a thousand miles begins with a single step”. Then reload the applet and view it again. c)In the Java code, on the line that is written: screen.drawString("Hello World",50,50); Change the value of the two numbers. Recompile and view the applet again. Do this several times. What do the two numbers each represent? Does it matter the order in which they are written?

Page 28: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 2-YOUR FIRST APPLET 13

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Page 29: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 2-YOUR FIRST APPLET 14

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Page 30: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 3-BASIC APPLET CREATION 15

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 3- BASIC APPLET CREATION

UNIT OVERVIEW

• 3.1 Basic Applet Framework

• 3.2 Your Second Applet with the paint method explained

• 3.3 Other built in methods

• 3.4 Rules for naming in Java

• 3.5 What does the word class mean in Java?

3.1 BASIC APPLET FRAMEWORK

NOTE: Although in section 3.1 there isn’t much hands on programming, it is critical that you read through this section carefully in order to understand the basic parts of a java program. There will be plenty of hands on exercises in the rest of the book!

All applets have the following basic framework. There are 4 parts to java programs: 1. Import lines -makes built in java words available for your program 2. Program heading line -this is where you name your program 3. Variable Section -lets you declare any specific java things you will be using 4. Methods -these are the instructions for the computer

EXAMPLE 3.1A IMPORT LINES AND PROGRAM HEADING LINE

import java.awt.*;

public class program_name extends java.applet.Applet {

Graphics screen;

public void init() {

} Everything that is in bold is what you would type. All of your other methods will eventually be located here. This method section is what tells the computer what to do }

1.Import section

2.Program heading section

4. Method section

The init method is blank right now, but it will be used to set up more complex programs when they first begin to run.

3. Variable Section We will almost always be drawing to the applet. So in most programs we use a Graphics type.

Page 31: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 3-BASIC APPLET CREATION 16

________________________________________________________________________ Copyright © 2000 Robbie Kailley

WHAT DO THE CURLY BRACES DO? The curly braces just indicate the beginning and ending of a program section. Curly

braces come in pairs { }. For every open one you have, you must have a closing one. You can see the init method has its own set of curly braces. As well, the very last closing curly brace always closes the beginning curly brace that is present on the program heading line. 1.IMPORT SECTION: WHAT DOES THE IMPORT DO?

For a java program to work, and compile, the location of all the special words in your program must be specified. All of Java’s special words are located in premade packages that are included with your JDK. There are packages for dealing with graphics, mouse clicks etc… The first line tells the compiler to go to the location on your computer where java is located and make available all the special words and symbols located in the java.awt package. Awt stand for abstract window toolkit, it contains all the premade special words with the proper instructions on how to do all the basic commands associated with applets and graphics. This is the only package we will be dealing with for now. We will deal with other packages later.

NOTE: Every time you want to use a special word, make sure the package that the word is defined in, is imported into your program. You are allowed to import more than one package. To determine what package a word or command you want use is in, you must use a guide that explains the java language. A common one available is called the api. You can download this from the same site where you downloaded the JDK. The api is a list (or dictionary) of all the special words in java, and what they do, and what package they come from.

2. PROGRAM HEADING SECTION: WHAT DOES THE PROGRAM HEADING LINE DO?

All of your java programs must contain this line. The only thing you can change is the name of the program. Later on we will be adjusting this line slightly. What this line does is create a new applet from the built in pre-made java applet template (that is what extends does in the program heading line). 3.VARIABLE SECTION: WHAT DO VARIABLES DO?

Variables will be explained in great detail in unit 5. For now you just need to type in the words as shown in the sample program.

In our sample program, we want to draw to the applet. We need to tell the computer to reserve some space for all our drawing information. So, we name our drawing area screen, and we tell the computer that screen holds Graphics information. 4. METHODS SECTION

Methods are sections of a program that perform certain instructions. As a programmer you can make your own methods and even give them your own name.The word public just means that the method is accessible from any part of the program. The word void will be explained in a more advanced course, for now just include it with all methods.

Page 32: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 3-BASIC APPLET CREATION 17

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 3.1B: METHOD STRUCTURE. Each instruction line must end with a semi-colon

public void methodname () { instructions; instructions; }

COMMENTS

Sometimes, you may want to insert comments or reminders about what a particular method or program does. To do this, you can type two front slashes (//) and whatever else is written on that line after the slashes is ignored by the compiler. It is just for you to read.

If your comment is going to be larger than one line enclose it between the following set of symbols /* put your comment in here and then when you are done end it with */

You should comment your code well, but not on every line. In many of the following programs in this book there will be comments to help explain what different instructions do. DO NOT PUT SEMI-COLONS AFTER A COMMENT IS FINISHED. EXAMPLE 3.1C BASIC APPLET FRAMEWORK WITH COMMENTS The full basic framework of a java program with comments (observe the pattern of

indenting, all examples will follow this pattern):

import java.awt.*; public class program_name extends java.applet.Applet { /*this is a dummy program which doesn’t really contain any instructions in the methods but it shows how the basic structure of a Java program looks like. Refer back to this example if you ever get stuck*/ public void init() { } //ends init method public method1 () { instructions; instructions; } //ends method1 public method2 () { //here is a one line comment instructions; instructions; } //ends method 2 } //ends class

Sometimes, there are special words that go inside the round brackets. These will be explained later. (Unit 5)

each method has its own set of curly braces to begin and end it

this curly brace ends the whole program, it matches up with the curly brace on the program heading line. MAKE SURE YOUR CURLY BRACES MATCH UP PROPERLY, THIS IS A COMMON ERROR

every instruction line ends with a semi-colon

this curly brace begins

the class (program)

Page 33: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 3-BASIC APPLET CREATION 18

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Sec 3.1 Mastery Questions

1.Add some comments to your hello world program. Recompile it and run it. Did the comments make any difference? 2.What were the methods in the hello world program from unit 2? 3. What does the import line do in a java program? 4.What must you make sure of when you are saving your java program and your web page that will display your applet (refer back to unit 2 if necessary)?

3.2 YOUR SECOND APPLET WITH THE PAINT METHOD EXPLAINED

Type in the following applet and compile it and then create a web page to view it. Save the applet as ex32.java EXAMPLE 3.2 A SIMPLE GRAPHICS APPLET WITH 2 RECTANGLES Applet draws 2 rectangles, one is filled, one is outlined

import java.awt.*; public class ex32 extends java.applet.Applet { Graphics screen; public void init() { } public void paint(Graphics screen) { screen.drawRect(30,30,50,50); screen.fillRect(100,100,20,20); } }

The web page code for example 3.2. Save it as web3.html,make sure its in the same

folder as the java program code.

<html> <applet code="ex32.class" height=400 width=400></applet> </html>

In this book, we will be focussing on creating applets, which are programs that can be

viewed on a web browser. You can create Java programs that can run without a web browser, these are called applications, but those will not be discussed in this book. To make an applet visible on your web browser, most often you will be using the paint method to do your drawing. The basic structure of the paint method is given with a brief explanation of how it works.

Page 34: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 3-BASIC APPLET CREATION 19

________________________________________________________________________ Copyright © 2000 Robbie Kailley

public void paint(Graphics screen) { drawing instructions; } The words in the round braces are called parameters. These are any variables that the method uses. The paint method is a built in method and by default, even though we have already declared a Graphics in the variable section, we need to still notify the paint method that it will be using that same Graphics variable. Most often, once you have declared a variable in the variable section, you do not need to notify each method which variables they will be using. Inside the paint method, now you can call up various pre-made methods available to the Graphics function. Section 3.2 Mastery Questions

1)Here are some sample instructions to draw to our screen. Add them to the paint method of your second applet, recompile the code then load the applet again. screen.drawRect(30,30,100,100); screen.drawOval(100,100,50,50); screen.setColor(Color.blue); screen.fillOval(250,250,40,40);

3.3 RULES FOR NAMING IN JAVA

If you have the choice to name something in Java, such as a program name or a

variable name (not a variable type such as Graphics, those are built in), there are certain restrictions.

• you may not have any spaces in the name (underscores are allowed)

• names cannot begin with a number

• besides the underscore, do not use any other symbols

• give all your variable and programs meaningful names

• you may not use special words already pre-built in the java language (called reserved words. A listing of common reserved words is in appendix A.

• do not name any of your variables with the same name as each other

• do not name any of your variables with the same name as your program

3.4 WHAT DOES THE WORD CLASS MEAN IN JAVA?

You may have noticed in the program heading line, it always begins with the words public class. The meaning of class in Java is a little advanced to introduce at this point but a basic definition will be given here. Class actually has 2 meanings in java

1. A program that a user has made. A blueprint for an applet. This is why you use the word class in your program heading line. It tells the computer that you are creating your own version of an applet, and then you provide all the instructions for your applet in the method section. There is much more to creating your own classes, this will be dealt with in Unit 14 and 15.

Page 35: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 3-BASIC APPLET CREATION 20

________________________________________________________________________ Copyright © 2000 Robbie Kailley

2. A reserved word that identifies a pre-made Java structure. For example, Graphics is a pre-made Java class, that means that Graphics has many of its own pre-made methods which may be used. This is why you can type in screen.drawString (“Hi”,50,50);

We know that screen is a Graphics class, which has many pre-built methods, one of which is drawString. To call up a method of a pre-built class, you use the general structure:

variable_name.method_name(parameters); For example in the above program we used the line: screen.drawRect(30,30,50,50);

To determine what the method needs to run, you will have to use the Java api reference, it tells you what each method for a particular class requires.

More on this in the variables unit (Unit 5).

UNIT EXERCISES

1.Fill in the blank a)A _________________ is created using //. b)The _______________section is where the instructions of the program are located. c) The compiler ignores _________________ when compiling your code. d)Every instruction line in java must end with a _______________________. e)The _________________ method has to have a Graphics parameter. f) To avoid a common compiling error, make sure your ___________________ match up in pairs. 2.Short Answer a)Which of the following are legal variable or program names, and which are not. Explain your reasons for each. may salary 4wheeler car2door phil_jackson jordan$ 3.Programming Questions a)Create an applet that displays the message as shown below I took the road less traveled and that has made all the difference b)Create an applet that draws a square or rectangle on the middle of the screen. (Hint: make sure you try section 3.2 mastery question, play around with the numbers)

Page 36: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 4-GRAPHICS 21

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 4 - GRAPHICS

UNIT OVERVIEW

• 4.1 Introduction to the Graphics class

• 4.2 The Java Coordinate System: An Introduction

• 4.3 Basic Methods of the Graphics Class:Creating Rectangles,Ovals, Arcs,Lines

• 4.4 Using the fill method

• 4.5 Using Colors

• 4.6 Creating Polygons

• 4.7 drawString and Changing Fonts

• 4.8 Creating your own methods and calling them from the paint method

4.1 INTRODUCTION TO THE GRAPHICS CLASS

As mentioned in the previous unit, the Graphics class is a pre-made java structure that contains many built in drawing methods. To draw in an applet examine table 4.1. Table 4.1 Basic steps in drawing in an applet Steps Example

declare a Graphics variable in the variable section

Graphics screen;

declare a paint method in the method section, make sure you are sending the Graphics variable to the paint method as a parameter

public void paint(Graphics screen) { instructions here; }

Inside the paint method: use your variable name in combination with all the Graphics methods to create your drawing.

public void paint(Graphics screen) { screen.drawRect(0,0,10,10); }

EXAMPLE 4.1 A SIMPLE GRAPHICS APPLET ILLUSTRATING ALL THE BASIC STEPS ABOVE Basic applet that displays 2 messages on the applet display

import java.awt.*; public class ex41 extends java.applet.Applet{ Graphics screen; //declaring a Graphics variable public void init() { } //ends init method public void paint(Graphics screen) { //we send our screen variable to the paint method screen.drawString("Welcome to unit4",50,50); screen.drawString("Now You will start programming",50,100); } //ends paint method } //ends example41

Save this program as ex41.java. From now on save all your programs with the same name as the name used in the program heading line

Page 37: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 4-GRAPHICS 22

________________________________________________________________________ Copyright © 2000 Robbie Kailley

WEB PAGE CODE FOR EXAMPLE4.1

<html> <applet code="ex41.class" height=400 width=400> </applet> </html>

4.2 THE JAVA COORDINATE SYSTEM: AN INTRODUCTION

The java coordinate system is shown below (the coordinates of the dots are estimated). Each point corresponds to a pixel unit. This is a term used to define distances on a display. You will get the feel for a pixel distance on your display as you play with the numbers in this unit. X Y Section 4.2 Mastery Questions:

1.If the square below represented a java applet with a size of 500,500, draw in the estimated location of the following points: a) 50,50 b) 400,10 c) 20,300 d) 250,250 e) 400,350

The outer limits of your x and y axis depend on your display

20,200

250,20

300,250

the numbers are written as <x,y>

0,0 starts here and increases in the x and y axis

Page 38: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 4-GRAPHICS 23

________________________________________________________________________ Copyright © 2000 Robbie Kailley

4.3 BASIC METHODS OF THE GRAPHICS CLASS:CREATING LINES, RECTANGLES, OVALS, ARCS

CALLING METHODS FROM THE GRAPHICS CLASS:

Example screen.drawLine(50,50,100,100); //this would draw a line.

You just have to know what parameters to send to the method and it will work. All of

the parameters must be whole numbers. If they are larger or smaller than the applet size then that part simply will not show on the display.

Now we will go through each of the basic methods and assume that the Graphics variable name in your program is screen. REMEMBER EACH OF THESE COMMANDS GO INSIDE THE PAINT METHOD, THAT IS WHERE THE DRAWING IS DONE. There is a complete example at the end of this section with all the basic shapes.

LINES:

General Structure screen.drawLine(starting x pixel,starting y pixel, ending x pixel, ending y pixel); Example screen.drawLine(10,30,100,50); This would draw a line from coordinate 10,30 to coordinate 100,50 This translates into: the starting point on the line is 10 pixels across and 30 pixels down the ending point on the line is 100 pixels across and 50 pixels down

<10,30>

<100,50>

name of Graphics variable the special graphics method used

Page 39: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 4-GRAPHICS 24

________________________________________________________________________ Copyright © 2000 Robbie Kailley

RECTANGLES:

General Structure screen.drawRect(upper left x pixel, upper left y pixel, width,height) screen.drawRoundRect(x,y,width,height,corner width,corner height); Example screen.drawRect(50,20,90,120); screen.drawRoundRect(100,20,90,120,10,5);

OVALS:

Ovals are drawn inside a boundary defined by a rectangle. The coordinates are written in the exact same way as the rectangle above.

Example screen.drawOval(50,20,90,120);

90 pixels wide

120 pixels height

<50,20> is starting point for upper left corner

90 pixels wide

120 pixels height

<50,20> is starting point for upper left corner

The outline rectangle will be invisible, it just shows the boundary of the oval. That is what your numbers in the method define

Same as the other rectangle except the corners are rounded. The larger the corner numbers, the more rounded the corners are

Page 40: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 4-GRAPHICS 25

________________________________________________________________________ Copyright © 2000 Robbie Kailley

ARCS: An arc is a segment of an oval. If you want to draw a part of a curve an arc will do

that for you.

General Structure screen.drawArc(x,y,width,height, start_angle,degrees from start angle to draw); The first 4 numbers define the oval that you will be drawing a section of. These numbers are exactly as defined in the oval section. The last 2 numbers tell which section of the oval you want to actually draw.

The following diagram shows how to determine angles:

Example screen.drawArc(50,150,90,120,0,180); This would draw an arc that started at 0 degrees and went 180 degrees (counter-clockwise) from that point. It would draw the top half of the oval.

0 degrees

90 degrees

180 degrees

270 degrees

starts at 0 degrees

sweeps 180 degrees across

Page 41: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 4-GRAPHICS 26

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Here is the sample code for the basic shapes we have just covered. Type it in and run it.The order in which you draw your shapes matters. For example, if you want a solid blue rectangle with yellow ovals on it, you must draw the blue rectangle first, then draw the yellow ovals. This order occurs in the paint method. EXAMPLE 4.3 BASIC SHAPES Applet draws all the basic shapes described in this section

import java.awt.*; public class ex43 extends java.applet.Applet { Graphics screen; public void init() { } public void paint(Graphics screen) { screen.drawLine(10,30,100,50); screen.drawRect(10,100,90,100); screen.drawRoundRect(200,100,100,100,30,10); screen.drawOval(10,250,90,120); screen.drawArc(200,250,90,120,0,180); } }//ends class

WEB PAGE CODE FOR EXAMPLE 4.3

<html> <applet code="ex43.class" height=400 width=400> </applet> </html>

NOTE: As you can see, the web page code is always the same, just with a different class name, which will run the applet you want. Now that you have seen how the web page code works, it will not be written underneath every java example. It is quite easy for you to do that on your own now. Don’t forget, you need to type out the web page to see any applet you have copied from this book or any applet you have made. Also, the size used for most of the applets in this book is height=400 width=400.

Section 4.3 Mastery Questions:

1. Make the following changes to example 4.3

• Change the size of the rectangle so it’s a square with sides of 150 pixels.

• Create a sad face inside of the rectangle. Use ovals for the eyes and nose, use an arc for the sad frown. Also use arc for eyebrows on top of the eyes

• Make the hair on top of the rectangle a series of lines that are standing straight up from the top of the rectangle.

Page 42: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 4-GRAPHICS 27

________________________________________________________________________ Copyright © 2000 Robbie Kailley

4.4 USING THE FILL METHOD

Another way to draw shapes is to have them solid. For example, instead of having an outline of an oval, you may want to have the oval filled in. You may want to do that for any kind of shape.

To fill in a shape, instead of using the drawRect , or the drawOval etc… functions, simply replace the word draw with the word fill. Leave all the coordinates the same.

Examples screen.fillRect(10,10,70,100); screen.fillOval(30,50,100,10); screen.fillArc(50,50,100,100,0,90);

Section 4.4 Mastery Questions:

1. In the program you made for section 4.3 mastery questions, fill the 2 eyes, and fill the sad smile.(Remember, the order of drawing matters)

4.5 USING COLORS

There are some basic colors that are included with Java, and you can also make your own colors. You must change the current color first, then draw the shapes you want. This will ensure that your shapes are the color you desire. You can change colors as many times as you want. USING BASIC JAVA COLORS

General Structure screen.setColor(Color._______); You would put the name of the color you want in the blank line. The basic colors which you are allowed you put on the blank line are: black,blue,cyan,gray,darkGray,lightGray,green,magenta,orange,pink,red,white,yellow EXAMPLE 4.5 BASIC JAVA COLORS Applets shows what various java colors look like

import java.awt.*; public class ex45 extends java.applet.Applet { Graphics screen; public void init() {} public void paint(Graphics screen) { screen.drawRect(50,50,50,50); screen.setColor(Color.blue); //changes current color screen.fillRect(100,50,50,50); screen.setColor(Color.red);//changes color screen.drawOval(150,50,50,50); screen.setColor(Color.yellow);//changes color screen.fillArc(150,100,50,50,0,180); } }//ends class

Page 43: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 4-GRAPHICS 28

________________________________________________________________________ Copyright © 2000 Robbie Kailley

CREATING YOUR OWN COLORS

The general structure for creating your own colors in Java requires the following at the beginning of your paint method for each color you want to make. Color __________=new Color(number for red,number for green,number for blue);

In the blank spot you would put the name of your new color.

In each of the spots in the round braces, you need to put a whole number representing how much of that particular color you want in your new color. The number can range from 0 to 255. It is possible to create almost any color from combinations of red,green and blue. The colors are called RGB colors. You can find RGB number combinations on Internet web sites.

Example To create red (although its already made) would look like this: Color my_red=new Color(255,0,0); To implement the color change use the following line: You only put your new color name inside the round braces. screen.setColor(my_red); NOTICE, this line is slightly different from the setColor used for basic pre-made Java colors. Premade Colors: screen.setColor(Color.red); //this has the word Color inside the braces Your Own Color: screen.setColor(my_red); //only the color name in the braces.

EXAMPLE 4.5B - USING YOUR OWN COLORS. Applet shows colors that are created by the user

import java.awt.*; public class ex45b extends java.applet.Applet { Graphics screen; public void init() { } public void paint(Graphics screen) { Color brown=new Color(107,69,38); Color myred=new Color(255,50,50); Color my_yellow=new Color(255,255,150); screen.drawRect(50,50,50,50); screen.setColor(brown); screen.fillRect(100,50,50,50); screen.setColor(myred); screen.drawOval(150,50,50,50); screen.setColor(my_yellow); screen.fillArc(150,100,50,50,0,180); } }//ends class

Page 44: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 4-GRAPHICS 29

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 4.5 Mastery Questions:

1.Change the colors of your eyes in the program you made in section 4.3. Also, change the color of the smile to a color that you make up.

4.6 CREATING POLYGONS

Polygons are multisided shapes. Table 4.6 Steps in using Polygons Steps Examples

declare a Polygon variable in the variable section: Initialize it in the init method.

Polygon mypoly; mypoly=new Polygon();

In the paint method, add points to the polygon

mypoly.addPoint(10,10);

When you are finished defining all your points, use any of the following to actually draw the polygon on the screen. (The computer will connect all your dots and close the polygons for you)

screen.drawPolygon(mypoly); or screen.fillPolygon(mypoly);

EXAMPLE 4.6 POLYGONS Applet shows a simple hexagon in the middle of the screen

import java.awt.*; public class ex46 extends java.applet.Applet { Graphics screen; Polygon mypoly; public void init() { } public void paint(Graphics screen) { mypoly=new Polygon(); screen.setColor(Color.blue); mypoly.addPoint(100,100); mypoly.addPoint(150,50); mypoly.addPoint(200,50); mypoly.addPoint(250,100); mypoly.addPoint(200,150); mypoly.addPoint(150,150); //automatically connects this point to the first point screen.fillPolygon(mypoly); } }//ends class

Section 4.6 Mastery Questions:

1.Using example 4.6 as a template, add a filled red 8 sided shape to your program adjusted in the last sections mastery question.

Page 45: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 4-GRAPHICS 30

________________________________________________________________________ Copyright © 2000 Robbie Kailley

4.7 DRAWSTRING AND CHANGING FONTS

The drawString method is one which you are already quite familiar with.

Example screen.drawString(“hello, welcome to the end of unit 4!”, 100, 100);

CHANGING FONTS It is possible to change the size and style of writing that shows on the applet display. You should know what types of Fonts are available on your system, or else you can just play around with the names and see if anything changes.

Example screen.setFont( new Font ("Courier", Font.BOLD,20));

EXAMPLE 4.7 DRAWSTRING AND FONT CHANGES Applet shows various messages in different fonts and sizes

import java.awt.*; public class ex47 extends java.applet.Applet { Graphics screen; public void init() { } public void paint(Graphics screen) { screen.setColor(Color.blue); screen.drawString("Almost done unit 4!", 50,100); screen.setFont( new Font ("Courier", Font.BOLD,20)); screen.drawString("What does this look like?",50,150); screen.setFont( new Font ("Helvetica", Font.ITALIC,20)); screen.drawString("What does this look like?",50,250); } }//ends class

Section 4.7 Mastery Questions

1.Add the Italicized word “stop”, in white writing to the 8 sided red shape you drew in Mastery section 4.6. 2.Add a blue name underneath your face, in a different font than the default one for your system (i.e. Helvetica etc..)

message to be printed x-position of message

y-position of message

FONT_NAME: put the name of the font you would like to try here. Some common ones are: TimesRoman,Serif,Courier,Arial etc…..

STYLE: this can be either PLAIN, BOLD, or ITALIC (all capitals)

SIZE: this can be a whole number, the largest and smallest size depends on your computer.

Page 46: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 4-GRAPHICS 31

________________________________________________________________________ Copyright © 2000 Robbie Kailley

4.8 CREATING YOUR OWN METHODS AND CALLING THEM FROM THE PAINT

METHOD

This chapter has gone through all of the basic shapes. Along the way you created a program and kept adding things to it. Sometimes drawing can get very complicated and the paint method can become very large and cluttered. Therefore, at this time, you will learn how to write your own simple methods and use them to help organize your program. This idea will be used for picture applets and for other types of programs later on in the book. CREATING YOUR OWN METHOD.

General Structure All of the bold faced items are the ones which you will fill in. The rest must be typed as shown. Methods shouldn’t be longer than 1 screen length. public void name(Graphics screen ) { instructions;

instructions;

instructions; }

TO CALL UP A METHOD FROM ANOTHER PART OF THE PROGRAM,

You need to send the Graphics variable to your new method because it needs it to draw on. You must write it inside the round braces when you call it up, which sends the Graphics variable to the method when it is called.

Example public void house(Graphics screen) { screen.drawRect(100,100,50,50); screen.drawLine(100,100,125,50); screen.drawLine(125,50,150,100); } //ends the house method public void paint(Graphics screen) { house(screen); }//ends paint

For more information on methods, read the Methods Interlude unit p.159. ADVANTAGES OF USING METHODS

Here’s the advantage of what methods can do to organize your program. Imagine drawing a scene of a house with a garage with a car in it. If you had to type all your code

To actually show the house on the screen, we must call up or activate the house method from inside the paint method.

Here is a method that will draw a small house. We indicate that the house method is expecting a Graphics variable by putting the

words Graphics screen in the round braces.

We are sending the Graphics variable screen to the house method because it is expecting it. It needs the screen to draw on.

Page 47: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 4-GRAPHICS 32

________________________________________________________________________ Copyright © 2000 Robbie Kailley

inside the paint method, it would become huge! Also if there was a problem, you would have to hunt through all the code to try to isolate which part drew what. Here is what the paint method of an organized program might look like: public void paint(Graphics screen) { houseframe(screen); windows(screen); chimney(screen); garage(screen); carbody(screen); carwheels(screen); }//end paint method

Can you see how much easier it is to tell what the program is doing. Of course you will still have to type all the drawing code, but it will be much easier to fix if there are problems and someone else can help you much easier also. EXAMPLE 4.8 USING METHODS IN A PROGRAM Applet draws a simple house with a chimney, showing the use of methods

import java.awt.*; public class ex48 extends java.applet.Applet { Graphics screen; public void init() { } public void paint(Graphics screen) { house(screen); chimney(screen); } public void house(Graphics screen) { screen.setColor(Color.blue); screen.drawRect(100,100,50,50); screen.drawLine(100,100,125,50); screen.drawLine(125,50,150,100); } //ends the house method public void chimney(Graphics screen) { screen.setColor(Color.red); screen.drawRect(100,50,15,50); }//ends the chimney method }//ends class

if you draw anything after this the color will be red, because the last setColor which was in chimney was red

you are sending screen to house so it can draw to it

Page 48: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 4-GRAPHICS 33

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 4.8 Mastery Questions

1.Why do you need to include the Graphics variable in the method calls described above i.e. house(screen); ? 2.What are some advantages of using methods in programming? 3.As a general rule of thumb what is the maximum length that a method should be? 4.Add a method to the example 4.8 program to make some windows on the house. Add another method to add a door to the house.

UNIT EXERCISES

1.Fill in the blanks a)______________________ help organize your program, making it easier to fix. b)The ________________ variable is what java needs to draw on. c)The last 2 numbers in the drawRect method describe the _______________ and __________ of the rectangle. d)The last 2 numbers in a drawArc method describe the __________________ and ____________ of the arc. e) _______________________ are always closed shapes even if the last and first point aren’t the same. 2.Programming Projects a)Create a scene using all of the shapes and ideas which were presented to you in this unit. Make sure you use methods to organize your program.

Page 49: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 4-GRAPHICS 34

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Page 50: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 5-VARIABLES 35

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 5 VARIABLES

UNIT OVERVIEW

• 5.1 What is a variable?

• 5.2 Declaring Variables, and the Assignment Statement

• 5.3 Java Variable Types

• 5.4 Constants

• 5.5 Java Math Functions

• 5.6 Casting

5.1 WHAT IS A VARIABLE?

To make programs useful, quite often we let the user enter in values for something. For example, if a program is meant to figure out the area of a rectangle, it would be useful to let the user enter in values for the length and width of the rectangle they wish to find the area of. Variables in Java enable programs to store values in the computer’s memory. Java can then access these values by calling up the location where the value is stored. It is just like using a formula in math. A formula always has variables in it. This enables a person to put whatever value they need into the formula to find a result. In summary a variable is a programming structure that lets a program store values of different types of data. Data can be whole numbers, decimal numbers, letters, words, symbols, or Java built in classes.

5.2 DECLARING VARIABLES, AND THE ASSIGNMENT STATEMENT

To use a variable in a Java program: Step 1: determine what type of data will be stored (these are pre-made Java types) Step 2: declare the variable in the variable declaration section Step 3: give a value to the variable immediately, or do it later in the program

STEP 1 DETERMINING DATA TYPE For example, a program may be created which prints a country. Since a country name

is a value (a word), we know we should declare a variable to store the country’s name. The type of data to be stored will be a String. The name of the variable will be country. You must follow the basic Java naming rules given in the previous units when naming variables. STEP 2 DECLARING THE VARIABLE: The declaration would look like: String country;

Page 51: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 5-VARIABLES 36

________________________________________________________________________ Copyright © 2000 Robbie Kailley

What is happening is the computer is reserving a space in its memory for a String value. The program must remember where in memory the value is stored, so the variable name is the “label” used to identify the memory location. In a diagram: (type String) Here is the blank space reserved in memory. It is labeled country. The only type of value that we can store in the blank space is a country word, because we have declared country to be a String variable. STEP 3 ASSIGN VALUE TO THE VARIABLE To assign a value to a variable, you use something called an Assignment Statement. The expression on the right hand side of the assignment operator (=) is the value and it is stored in the variable written on the left side of the assignment operator. You can use the assignment operator in any method in your program. (Any variables you need in order for your applet to begin, will be assigned values in the init method. REMEMEBER, the init method is run only once the first time that your applet is displayed)

Example country=”Canada”;

In a diagram: (type String) Here the space reserved in memory called country now has the value Canada stored in it. country

You can change the value in country many different times in a program. In that case all you are doing is replacing the value inside the memory box. (see example 5.2)

NOTE: If you try assigning a number into the country variable, you would get an error. Only the data type declared is allowed into the variable. In this case, since the data type is a String, then only String values can go into the country variable.

Canada

Page 52: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 5-VARIABLES 37

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Examples for declaring variables (in the variable declaration Section) String my_name; int salary; Examples for Assigning Values to Variables (in any method) my_name=”Bob”; salary=10000;

EXAMPLE 5.2 SIMPLE VARIABLE DECLARATION AND USE IN DRAWSTRING Applet prints out the words Canada and France on the display

import java.awt.*; public class ex52 extends java.applet.Applet { Graphics screen; String country; //this is the variable to hold the name of a country public void init() { } public void paint(Graphics screen) { country="Canada"; //this gives the variable country a //value of canada screen.drawString(country,100,100);//this prints out the //value of country //since country is a variable, we can change its value //We now make the current value of country become France country="France"; screen.drawString(country,100,300); } }//ends ex52

data-type your variable name

variable name the value being assigned to the

variable

Page 53: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 5-VARIABLES 38

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 5.2 Mastery Questions

1.Which of the following variable declarations contain errors? (Explain your answers) a) String $myname; b) my_name String; c) String my_name. d)String myname2; 2.Which of the following assignment statements contain errors? (Explain) a) my_name=: “Bob”; b) name=”Bob”; c)name:=”bob”; 3.Adjust the example program and add another variable called city. Print out 2 different values for this variable.

5.3 JAVA VARIABLE TYPES

There are several basic data type built into java. Determine what type of data you will be storing then declare and assign a value to the variable. Table 5.3-Table of Variables Data Type Description Example

int a whole number,values from -2 billion to 2 billion

10, -10

long a whole number values from -9E18 to 9E18

3,000,000,000,000

double a decimal number from -1.7E308 to 1.7E308

102.998E48

char a single character from the keyboard.Must be enclosed in single quotes ‘r’

‘r’ ‘&’ ‘*’

String a combination of characters, must be enclosed in quotes “ word “

“Henry” “Jane”

boolean a variable whose value can either be true or false

the value is either true or false (more detail in unit 6)

To print out the value of a variable in the drawString method, you put an empty pair of

quotation marks, then the + sign, then the variable name as the first parameter. GENERAL STRUCTURE FOR PRINTING VARIABLE VALUES

screen.drawString(“” +variable_name, 50,50); You could also print more than one variable on the same line. screen.drawString(“”+variable1+variable2+variable3+”the end”, 50,50);

the Estands for x10 n. ex. 1.2E4 is 1.2x104

Page 54: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 5-VARIABLES 39

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 5.3 USING AND PRINTING ALL THE VARIABLE TYPES Applet displays many different words and numbers representing all variable types

import java.awt.*; public class ex53 extends java.applet.Applet { Graphics screen; String country; char letter; int wholenumber1; long wholenumber2; double decimalnumber1; boolean running; public void init() { country="Canada"; letter='r'; wholenumber1=1000; wholenumber2=100000000; decimalnumber1=0.23443; running=false; } public void paint(Graphics screen) { screen.drawString(country,100,10); screen.drawString(""+letter,100,20); screen.drawString(""+wholenumber1,100,30); screen.drawString(""+wholenumber2,100,40); screen.drawString(""+decimalnumber1,100,50); screen.drawString(""+running,100,60); //printing more than one variable on one line screen.drawString("Number1 "+wholenumber1+" Number2 "+wholenumber2,100,70); screen.drawString(""+running+letter+"country"+country,100,80); } }//ends ex53

Section 5.3 Mastery Questions

1.What type of data-type would you use to store the following values a) & b) “Kate” c) 12.44 d) -12.9983 e) 12321 2.Add the following to the Example 5.3 program. Create variables for your name, number,favorite movie,favorite song,favorite letter, and favorite tv show. Print out the variable values on the applet display.

In this method, I will initialize all the variables. You can initialize the variables in any method you want. Just make sure you initialize the variable before you print it, or use it in a calculation. If you don’t the applet will not know the value for the variable and you will get an error.

Notice the letter is in single quotes

Page 55: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 5-VARIABLES 40

________________________________________________________________________ Copyright © 2000 Robbie Kailley

5.4 CONSTANTS

Constants are similar to variables except they hold a particular value for the whole program. Their value stays constant the whole program. Constants can be useful when using values for things such as tax rates or interest rates.

Example final double tax=1.14; This declares tax to be 1.14 throughout the whole program. So if you want to change the tax rate, you would simply change the value in the constant declaration.

EXAMPLE 5.4 USING A CONSTANT Applet displays the value of the constant called tax

import java.awt.*; public class ex54 extends java.applet.Applet { Graphics screen; final double tax=1.14; public void init() { } public void paint(Graphics screen) { screen.drawString("The tax rate is"+tax,100,100); } }//ends ex54

Section 5.4 Mastery Questions

1.What is the advantage of using constants? 2.Declare a constant for your name for example 5.4 Program. Then use drawString to print out the value of your constant.

5.5 JAVA MATH FUNCTIONS

Quite often computer programs are required to do mathematical operations. There are only 5 basic math operations that java has. The basic orders of operations that you have learned in Math class apply here. Table 5.5 Math Operators Operator Operation Example

+ adds numbers 2+3 or num1+num2

- subtracts numbers 2-3 or num1-num2

* multiplies numbers 2*3 or num1*num2

/ divides numbers 2/3 or num1/num2

% gives integer remainder 3%2 would equal 1

add the word final before the data type in the variable declaration

data-type variable_name

value

Page 56: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 5-VARIABLES 41

________________________________________________________________________ Copyright © 2000 Robbie Kailley

A math operation can be used with numbers or with variables that contain number

values. Also, you can put a math operation on the right side of an assignment statement and the result of that math operation will be stored to the variable on the left side of the assignment statement.

Example Let’s assume salary is a double variable type (decimal number) salary=15.35*8*4; This would assign the value of the equation on the right side to the variable salary. or if the pay_rate was a variable, then the expression could also look like this. salary=pay_rate*8*4; **You must make sure you have a value for pay rate before the above line is written, or else the computer will give you an error because it doesn’t have all the information to complete the expression on the right side.

NOTE: If salary was an integer type of variable then this would cause an error, because the expression on the right side will be a decimal number and you are trying to store that into a integer variable. To help avoid this, casting can be used (section 5.6)

EXAMPLE 5.5 USING BASIC MATH OPERATIONS Applet shows all the basic math functions using whole numbers and decimal numbers

import java.awt.*; public class ex55 extends java.applet.Applet { Graphics screen; int num1,num2,addint,subint,multint,modint,divint; double payrate,hoursworked,salary; public void init() { num1=30; num2=16; payrate=12.00; hoursworked=8; salary=payrate*hoursworked; } public void paint(Graphics screen) { addint=num1+num2; subint=num1-num2; multint=num1*num2; divint=num1/num2; modint=num1%num2; screen.drawString(""+num1+"+"+num2+" = "+addint,100,10); screen.drawString(""+num1+"-"+num2+" = "+subint,100,20); screen.drawString(""+num1+"*"+num2+"= "+multint,100,30); screen.drawString(""+num1+"/"+num2+" = "+divint,100,40); screen.drawString(""+num1+"mod"+num2+"="+modint,100,50); screen.drawString("Hours: "+hoursworked,100,70); screen.drawString("Payrate:$ "+payrate,100,80); screen.drawString("Total is$ "+ salary,100,90); } }//ends ex55

divint as an integer will give the quotient as an integer if you made divint as a double, it will give the quotient as a decimal number (more accurate)

Page 57: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 5-VARIABLES 42

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 5.5 Mastery Questions

1.What is the value of the following expressions? a) 5*3/2 b) (5*3)/2 c) 12%4 d)12%5 e) (((3+12)*2)-3)%8 2.Adjust example 5.5 so it also calculates how much a person would earn in a year, and in 10 years. Create separate variables for each value. When printing out the values, put them in a sentence explaining what the number is representing.

5.6 CASTING

This forces an expression in an assignment statement into a particular data type.

Example Keys is declared as an integer variable and we are trying to assign the value of 9.0/2.5 to it. Normally we would get an error because we are trying to assign a decimal value to an integer variable type. To avoid this casting is used. keys=(int) (9.0/2.5); This would take the expression 9.0/2.5 and round it to a whole number. Then it can be assigned to the integer variable called keys.

EXAMPLE 5.6 CASTING This example will cast a decimal(double) into an integer value: Note the rounding

import java.awt.*; public class ex56 extends java.applet.Applet { Graphics screen; double payrate,hoursworked; int salary; //salary is declared as an integer public void init() { payrate=12.44; hoursworked=8.32; salary=(int)(payrate*hoursworked); } public void paint(Graphics screen) { screen.drawString("Hours: "+hoursworked,100,70); screen.drawString("Payrate:$ "+payrate,100,80); screen.drawString("Total is$ "+ salary,100,90); } }//ends ex56

math expression

what data-type you are converting the expression to.

Integer variable to store result

the result of multiplying payrate*hoursworked is going to be a decimal(double). However, we have decided we want to store the result in integer form in a variable called salary, so we must cast the operation into an integer

Page 58: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 5-VARIABLES 43

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 5.6 Mastery Questions

1. Write the expression that would cast the result of 10/2 into a double variable called pizza_slices. 2.Add the following int variables to example 5.6: families, total_children Add the following double constant to example 5.6 : average_children Put in the following values: families = 1 000 000 : average_children= 1.7 Determine the result of total_children and print it out. (Remember, total_children is an integer variable) ***NOTE: A sample program that is fully commented which shows how to format

decimal numbers is available on the book website: http://www3.telus.net/javastarter

UNIT 5 EXERCISES

**For all programs use variables and constants where appropriate** 1.Write a program that produces the following chart of student numbers in courses Physics 20 Chemistry 24 Math 20 Total 64 Have the computer perform the calculation on the last line. 2.The formula for the area of a circle is pi*radius*radius. Create a program that calculates the area of a circle if the radius is 3.60 cm. (assume the value of pi=3.14) 3.Write a program that displays the following output. (Let the computer do the calculation) 7*1 is 7 7*2 is 14 7*3 is 21 7*4 is 28 4.Write a program that shows how a $100 bill can be broken down into 20’s, 10’s, 5’s , 2’s and 1’s. Let the computer do the calculations. For example: $100 can be broken into 5 - $20 bills 5.Assuming the tax rate is 14%, write a program that calculates and outputs the total of the following bill. (This complete bill should be printed with the blanks filled in.) Let the computer do the calculation. shirt $30 shorts $20 sub-total ____ tax ____ total ____

Page 59: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 5-VARIABLES 44

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Page 60: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 6-GRAPHICAL USER INTERFACE I-OUTPUT COMPONENTS 45

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 6-GRAPHICAL USER INTERFACE I-OUTPUT COMPONENTS

UNIT OVERVIEW

• 6.1 What is a Graphical-User-Interface, what is a component

• 6.2 The Basic Steps for Creating Components in your program

• 6.3 Basic TextField and TextArea methods-Obtaining and Displaying Information

• 6.4 Converting TextField information into Numbers for Calculations

6.1 WHAT IS A GRAPHICAL USER INTERFACE, WHAT IS A COMPONENT?

A Graphical User Interface (GUI) refers to the various “pieces” that a program has which lets a user interact with the program. Each individual type of piece is called a component. For example, buttons, checkboxes and menu bars are all components that make up the GUI of many programs. In Java creating an effective GUI using the various components is essential to creating useful user-friendly programs.

6.2 THE BASIC STEPS FOR CREATING COMPONENTS IN YOUR PROGRAM

BASIC DEFINITIONS A textfield is a maximum of one line long. It is simply a place where the user can enter in some data. A textarea is similar to a textfield except it is more than one line long. It is used to display large amounts of textual data. A button is a component that will make something happen when it is pressed. A Label is just writing that you can place on the screen, beside TextFields,TextArea etc... A label is a little easier to use than drawString.

NOTE: There is no Graphics variable type and no paint method in any programs in which there is no drawing done. In this chapter, all we are doing is adding components, this is different than drawing on the surface of the applet display. Therefore, the programs in this unit do not have a paint method or a Graphics variable.

There are many different types of components in Java. We will tackle the more common ones in this unit and unit 8. To create and display any component, the following steps must be taken:

Page 61: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 6-GRAPHICAL USER INTERFACE I-OUTPUT COMPONENTS 46

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Table 6.2 Declaring and using components in applets Step Example

declare the component in the variable declaration section.

TextField entername; TextArea printname; Button submit; Label enter,print;

add the line setLayout(null) to the init method. This lets you customize your components by placing them wherever you want on the applet display. Without this line the computer will automatically place your components in the order you add them, completely ignoring your coordinates given.

setLayout(null);

initialize all the components in the init() method

entername=new TextField(5); printname=new TextArea(5,10); submit=new Button("Press"); enter=new Label("Your name"); print=new Label("Output name");

Here we are resizing the components to specific rectangular regions defined by coordinates supplied. setBounds(x,y,width,height);

entername.setBounds(100,10,50,50); printname.setBounds(100,100,50,50); submit.setBounds(180,50,50,20); enter.setBounds(10,10,80,20); print.setBounds(10,100,80,20);

add the component to the applet display

add(entername); add(printname); add(submit); add(print); add(enter);

size of textfield, in character length

size in rows and columns

The word in the quotes is what is written on the button

the caption of the label

the numbers stand for x,y,width,height

Page 62: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 6-GRAPHICAL USER INTERFACE I-OUTPUT COMPONENTS 47

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 6.2 ADDING THE BASIC COMPONENTS TO YOUR DISPLAY Applet creates a textfield,textarea, button and a label on the display

import java.awt.*; public class ex62 extends java.applet.Applet { TextField entername; TextArea printname; Button submit; Label enter,print; /*this declares 2 labels to be used, one will be beside the TextField, the other will be beside the TextArea*/ public void init() { setLayout(null); //Here we initialize all the components with the proper beginning information entername=new TextField(5); //the 5 specifies the length of the line printname=new TextArea(5,10); //text area of 5 rows and 10 columns submit=new Button("Press"); //the name "Press" is on the button on the display enter=new Label("Your name"); //this will be the TextField label print=new Label("Output name"); //this is the TextArea Label //Here we set all the components coordinates entername.setBounds(100,10,50,50); printname.setBounds(100,100,50,50); submit.setBounds(180,50,50,20); enter.setBounds(10,10,80,20); print.setBounds(10,100,80,20); //Here we are adding the components to the applet so they will show up add(entername); add(printname); add(submit); add(print); add(enter); } }//ends class ex62

Section 6.2 Mastery Questions

1.What do the 4 numbers in the setBounds method stand for? 2.Why do we use setLayout(null) in the init() method? 3.Add 2 more textfields to your applet display. Label them number1, number2. Make sure they are placed one above another. Then underneath them both, add a textarea that has a label called answer.

This line lets you place your components wherever you need. You must include this line if you want to use setBounds to place all your components

the 4 numbers stand for x,y,width,height on the display

Page 63: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 6-GRAPHICAL USER INTERFACE I-OUTPUT COMPONENTS 48

________________________________________________________________________ Copyright © 2000 Robbie Kailley

6.3 BASIC TEXTFIELD AND TEXTAREA METHODS-OBTAINING AND

DISPLAYING INFORMATION

When using TextFields and TextAreas to input and output information, there are a number of useful methods that can be used. A summary of the methods is provided in table below with detailed explanations following the table. Table 6.3 Summary of basic TextArea/TextField methods Method Explanation Example

getText(); gets the current information from a textArea/Field in String form

input.getText();

setText(); puts in text into the desired area,replacing whatever was there before

input.setText(“Hello”);

append(); adds text to previously existing text in a TextArea/Field

input.append(“add this”);

“\n” place a return after printed statement input.append(“Hi”+”\n”);

setEditable(); decides whether a user can change the information in a TextArea/Field

input.setEditable(true); or input.setEditable(false);

GETTEXT() METHOD

Use: to obtain information from a TextField or TextArea

Steps Example

1. Declare a new String variable that will store the information from the TextField or TextArea.

String thename;

2. Use the getText() method to obtain the information from the desired TextField or TextArea and then assign it to the variable you have created. For the example, assume the name of the TextField is enter_name,

thename=enter_name.getText();

SETTEXT() METHOD

Use: This method erases all the current information in a TextField or TextArea and replaces it with the new information given.

Example enter_name.setText(“Descartes”); enter_name.setText(“the name is”+name1); enter_name.setText(“Hello”+name+”welcome to java”);

the value from enter_name TextField is

obtained and stored in the variable called thename

this will print the words and the value of the variable name1

this prints out hello and then the value of name

variable and finally

welcome to java

Page 64: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 6-GRAPHICAL USER INTERFACE I-OUTPUT COMPONENTS 49

________________________________________________________________________ Copyright © 2000 Robbie Kailley

APPEND() METHOD Use: The append command adds to previously existing information in a

TextArea

Example print_name.append(“This adds to current text”);

“\N” SYMBOL

Use: Add the combination of symbols “\n” to the end of an append to create a return.

Example print_number.appendText(“Here is an example of a return”+ “\n”); print_number.appendText(“the next line appears underneath”);

The output of the above lines would be:

Here is an example of a return the next line appears underneath

If we didn’t use the special characters, the output would be:

Here is an example of a return the next line appears underneath

SETEDITABLE() METHOD

Use:Decides whether a user can edit/change the information in a TextField or TextArea. This is very useful if you want to use a specific TextArea or TextField to only display information and you don’t want the user to be able to change the information in any way.

Example print_name.setEditable(false); print_name.setEditable(true);

this would add the words after whatever is currently in the textarea. It will not erase what was previously there

the print_name textarea information cannot be changed

the print_name textarea

information can be changed

Page 65: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 6-GRAPHICAL USER INTERFACE I-OUTPUT COMPONENTS 50

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 6.3 BASIC TEXTAREA/TEXTFIELD METHODS Applet gets the values from the textfields and display them in various ways in textareas

import java.awt.*; public class ex63 extends java.applet.Applet { TextField input1,input2,input3; TextArea output1,output2; String value1,value2,value3; //these will hold the string values of the information stored in input1,2,3 public void init() { setLayout(null); //initializing the textfields input1=new TextField(5); input2=new TextField(5); input3=new TextField(5); output1=new TextArea(5,10); output2=new TextArea(5,10); //setting the coordinates input1.setBounds(10,10,100,100); input2.setBounds(120,10,100,100); input3.setBounds(250,10,100,100); output1.setBounds(10,150,200,200); output2.setBounds(220,150,200,200); //adding the components to the display add(input1); add(input2); add(input3); add(output1); add(output2); //textfield input1,input2,input3 are given values input1.setText("Be"); input2.setText("Proactive"); input3.setText("Always"); //store the value of each textfield in a String variable value1=input1.getText(); value2=input2.getText(); value3=input3.getText(); //output the values of each in TextArea 1 output1.setEditable(true); output1.setText(value1+value2+value3); //output the values using append in many different ways output2.setEditable(false); output2.append(value1); output2.append(value2); output2.append(value3+"\n"); //the "\n" places a return at then end of the current line output2.append(value3+value2+value1+"\n"); output2.append(value1+"\n"); output2.append(value2+"\n"); output2.append(value3+"\n"); } }//ends class

this textarea is set as noneditable so you cannot type inside of it to change the words. Try it.

this textarea is set as edittable, so you can type in it to change the words inside. Try it.

Page 66: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 6-GRAPHICAL USER INTERFACE I-OUTPUT COMPONENTS 51

________________________________________________________________________ Copyright © 2000 Robbie Kailley

SubSection 6.3 Mastery Questions

1.Make the first TextArea non-editable and the second area editable. 2.Change the words in the first textfield to “Become” 3.Add another TextField called input4, put the words “It works” in it. Add these words to the output areas in the same method as was used for the other TextFields.

6.4 CONVERTING TEXTFIELD INFORMATION INTO NUMBERS FOR

CALCULATIONS AND OUTPUTTING THE RESULTS

Many times we want to perform some mathematical operation on numbers which have been entered into textfields. The problem is that so far, we can obtain information from a textfield and store it as a String. We cannot multiply/divide/add or subtract Strings! We need to convert the information from a String into a number, then we can perform mathematical operations with it. CONVERSION EXAMPLE Lets assume you have already declared a TextField called number1, and a String variable called wordnumber. Table 6.4 Converting Strings into numbers Steps Example

First you must decide what type of number you will be storing from the textfield. Declare a variable of that type.

int num1;

Obtain the information from the textfield and store it as a String (as shown in one of the examples above)

wordnumber=number1.getText();

Then use any one of the following methods to convert the String called wordnumber into a number.

if num1 is an integer: num1=Integer.valueOf(wordnumber).intValue(); if num1 is a double ( decimal number) num1=Double.valueOf(wordnumber).doubleValue();

Then you can do any mathematical computation with num1.

OUTPUT EXAMPLE

Outputting a number in a TextArea is very similar to outputting a String in a TextArea. You can use the appendText or the setText command to output to a textarea.

Page 67: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 6-GRAPHICAL USER INTERFACE I-OUTPUT COMPONENTS 52

________________________________________________________________________ Copyright © 2000 Robbie Kailley

If print_number is the name of our TextArea, here are some examples of how to output a number. (assume num1,num2 are integer variables, and that name is a String

variable) Table 6.4b Outputting numbers in TextArea

Steps Example

This will just print the value of num1. You need to have the empty quotes in the front

print_number.appendText(“” + num1);

This will print the value of num1 followed by the words “is my number”

print_number.appendText(“”+num1+”is my number”);

You can put in as many number values as you want, just keep using the + sign. You can mix number with words, by using the + sign and putting the words in quotes.

print_number.appendText(name+”favorite number is”+num1+”and second is”+num2); or print_number.appendText(“My favorite number is” + num1);

EXAMPLE 6.4 CONVERTING STRING TO NUMBERS AND PERFORMING MATH OPERATION Applet takes in 2 numbers from the user and adds them,outputting total when button is

pressed

import java.awt.*; public class ex64 extends java.applet.Applet { TextField num1,num2; TextArea total; String wordnum1,wordnum2; int firstnumber,secondnumber,addedtotal; public void init() { setLayout(null); num1=new TextField(5); num2=new TextField(5); total=new TextArea(5,10); num1.setBounds(30,30,100,25); num2.setBounds(30,60,100,25); total.setBounds(30,90,300,50); add(num1); add(num2); add(total); num1.setText("50"); num2.setText("25"); wordnum1=num1.getText(); wordnum2=num2.getText(); firstnumber=Integer.valueOf(wordnum1).intValue(); secondnumber=Integer.valueOf(wordnum2).intValue(); addedtotal=firstnumber+secondnumber; total.setText("The total of "+firstnumber+" and "+secondnumber+" is "+addedtotal); } }//ends class

requires empty quotes

getting and storing the values of num1 and num2 textfield in String variables

converting the value of the String variables into //actual numbers and storing them in int variables

outputting the value of the numbers added . Notice how the int variables and Strings are combined

setting the position of the components

initializing the textfield and textareas

adding the components to the display

putting in values for num1 and num2 textfields

Page 68: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 6-GRAPHICAL USER INTERFACE I-OUTPUT COMPONENTS 53

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Sub-Section 6.4 Mastery Questions

1.Create another TextArea and only print out the addedtotal 2.Create other variables so you can also output the result of subtracting,multiplying, and dividing the 2 numbers. 3.Add another TextField, so now you can use another number in your adding,subtracting, etc… calculation. 4.Add labels to all the TextAreas and TextFields

UNIT EXERCISES

***For all programs,use variables to store and calculate information*** 1.Create a program that displays a 3 digit number in a textfield. Then in the textarea, show the number in the 100’s place, 10’s place, 1’s place. (i.e. if the number is 456 then the output would be: 4 - hundreds 5 - tens 6- ones). The computer should perform a calculation to determine the output. 2.Create a program that takes a certain amount of change, and breaks it down into quarters,dimes,nickels and pennies. For example, 69 cents is broken down as follows: 2-quarters 1-dime 1-nickel 4-pennies. Show the initial amount in a textfield, show the broken down amounts in a textarea. 3.Create a program that has separate textfields for a persons name,address and phone number. Have the total information output in a textarea in an organized fashion.

Page 69: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 6-GRAPHICAL USER INTERFACE I-OUTPUT COMPONENTS 54

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Page 70: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 7-GRAPHICAL USER INTERFACE -BASIC INPUT AND EVENT 55

HANDLING

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 7 GRAPHICAL USER INTERFACE- BASIC INPUT AND EVENT HANDLING

UNIT OVERVIEW

• 7.1 What is Event Handling

• 7.2 Basic Steps in Event Handling

• 7.3 Using the actionPerformed method to store instructions

• 7.4 Using repaint() method to recall the paint method

7.1 WHAT IS EVENT HANDLING

To enable java programs to have user-interaction, we must use Events. An event is anything that occurs on the applet display. It may be the movement of the mouse, a mouse click, a button press etc… Telling the computer what to do if an event occurs in your component (i.e. clicking of a mouse) will enable your programs to be more responsive to user-actions and of course be more user-friendly. In this unit, we will be using Events to handle the click of buttons. When the user clicks a button, the program will know its time to perform some specific instructions. In the previous unit, all the data was preprogrammed, so there was no need for user interaction. This limits the usefulness of the program. You want the user to be able to enter, and even change the data and see what happens. For example, if a program is going to calculate the total of a purchase, you don’t want the amount of the purchase preprogrammed in. You want the user to be able to enter in their own amount as many times as they want, and calculate the total each time.

7.2 BASIC STEPS IN EVENT HANDLING

To handle events you must do several things.

STEP 1: ADDING AN INTERFACE TO YOUR PROGRAM: Decide what type of event is to be handled, and add the proper import

statement and interface to the program heading line. This enables the applet to recognize and call up Java’s built in code to handle certain types of events. All of Java’s interfaces have the ending listener. For example: ActionListener (deals with buttons), MouseListener, KeyListener (keyboard events) etc… The idea is that when you add a listener to your program, it will “listen” for certain type of events while the applet is running.

Example import java.awt.*; import java.awt.event.*; //this adds the event code to the current applet for use public class ex64 extends java.applet.Applet implements ActionListener {

Page 71: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 7-GRAPHICAL USER INTERFACE -BASIC INPUT AND EVENT 56

HANDLING

________________________________________________________________________ Copyright © 2000 Robbie Kailley

As you can see, we have changed the program heading line a little. The

ActionListener class is a built in java class that helps your applet handle events in Buttons, and TextFields. It is similar to the import idea at the beginning of Java program. The reason why its added on the program heading line is a little advanced for this course, but suffice it to say, that it has to do with the structure of the built in code. STEP 2: ADDING LISTENERS TO THE COMPONENT YOU WANT TO MONITOR FOR EVENTS.

This adds the listeners to the specific components you want to check on. For example, you may have 10 TextFields but you only want to check for events in one of them. By adding a listener only to that textfield, it will make the program run faster and take up less memory.

Example Assume we have created a button called submit. submit.addActionListener(this); The (this) just refers to the current applet. So the translation would read something like: To the Button called submit in this applet, add an ActionListener. (which monitors the button for events)

STEP 3 BUILT IN METHOD FOR EVENT HANDLING

You must add the built in method for handling the event, in case the event occurs. You have to fill the method with your own instructions.

The built in method for ActionListener is called actionPerformed. It does have a parameter called ActionEvent. Later this will help us identify what component the event occurred on. For example, if we had 3 buttons in the program we need some way of doing a different set of instructions depending on which button is clicked. For now, we will have only one button, so our method will contain just the instructions for that button.

Example public void actionPerformed(ActionEvent event) { instructions; instructions; }

We have not added any instructions to the method yet, lets do that in the next section.

Page 72: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 7-GRAPHICAL USER INTERFACE -BASIC INPUT AND EVENT 57

HANDLING

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 7.2 BASIC STRUCTURE OF EVENT HANDLING Applet displays a textfield a textarea and a button labeled press

import java.awt.*; import java.awt.event.*; //notice the additions to the import and program heading //section public class ex72 extends java.applet.Applet implements ActionListener { TextField entername; TextArea printname; Button submit; Label enter,print; public void init() { setLayout(null); entername=new TextField(5); printname=new TextArea(5,10); submit=new Button("Press"); enter=new Label("Your name"); print=new Label("Output name"); entername.setBounds(100,10,50,50); printname.setBounds(100,100,350,50); submit.setBounds(180,50,50,20); enter.setBounds(10,10,80,20); print.setBounds(10,100,80,20); submit.addActionListener(this); //adds the listener to the button add(entername); add(printname); add(submit); add(print); add(enter); } //the next method is the built in method that must be //included when handling events. It is empty right now //but in the next section we will be adding //instructions to it public void actionPerformed(ActionEvent event) { } }//ends class ex72

Section 7.2 Mastery Questions

1. Why is it an advantage to have to add an actionListener to each component individually?

Page 73: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 7-GRAPHICAL USER INTERFACE -BASIC INPUT AND EVENT 58

HANDLING

________________________________________________________________________ Copyright © 2000 Robbie Kailley

7.3 USING THE ACTIONPERFORMED METHOD TO STORE INSTRUCTIONS The actionPerformed method holds all the instructions which are meant to occur when the

event happens. To get information from textfields and output to textareas we will be using most of the TextField and TextArea methods you learned in unit 6. In our example program 7.2, the actionPerformed method automatically occurs when any of the components which has an actionListener added to it, has been acted upon. So, the only component in our program with an actionListener is the Button. If the button has been clicked, then all of the instructions inside the actionPerformed method will then be followed. The applet (program) is always running, so the user can type in another name, press the button and the message in the TextArea will be adjusted.

Note:Although it is possible to add a listener directly to a TextField (called a FocusListener), in this book we will be adding buttons to our applets which the user can press to indicate when they want something to occur.

EXAMPLE 7.3 FULL EXAMPLE OF INPUT AND OUTPUT USING EVENTS Applet lets user enter in their name. Upon pressing button, a message prints in textarea.

import java.awt.*; import java.awt.event.*; public class ex73 extends java.applet.Applet implements ActionListener { TextField entername; TextArea printname; Button submit; Label enter,print; String name; public void init() { setLayout(null); entername=new TextField(5); printname=new TextArea(5,10); submit=new Button("Press"); enter=new Label("Your name"); print=new Label("Output name"); entername.setBounds(100,10,250,50); printname.setBounds(100,100,350,50); submit.setBounds(180,70,50,20); enter.setBounds(10,10,80,20); print.setBounds(10,100,80,20); submit.addActionListener(this); //adds the listener to button add(entername); add(printname); add(submit); add(print); add(enter); } public void actionPerformed(ActionEvent event) { name=entername.getText(); printname.setText("Hello "+name+". You clicked the button"); } }//ends class ex73

This method is the built in method that must be included when handling events.It gets the name from the textfield and stores it in a String variable, then outputs it in a textarea.

Page 74: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 7-GRAPHICAL USER INTERFACE -BASIC INPUT AND EVENT 59

HANDLING

________________________________________________________________________ Copyright © 2000 Robbie Kailley

USEFUL BUTTON METHOD

In many programs you will have more than one button. You may want to do different instructions depending on which button is pressed. In unit 8, section 8.2, example 8.2a you will be shown how to make decisions based on which button has been pressed. In this section, you will be shown how to identify a button in the actionPerformed method by retrieving its label.

Example: Assume we have declared buttonpressed as a String variable public void actionPerformed(ActionEvent event){ buttonpressed=event.getActionCommand(); }

EXAMPLE 7.3A DISPLAYING BUTTON LABELS USING ACTIONEVENTS Applet displays label of button pressed in TextArea: there are 2 buttons

import java.awt.*; import java.awt.event.*; public class ex73a extends java.applet.Applet implements ActionListener{ TextArea output; Button but1,but2; String buttonpressed; //stores the label of the button public void init() { output=new TextArea(20,30); add(output); but1=new Button("Button1"); but2=new Button("Button2"); but1.addActionListener(this); but2.addActionListener(this); add(but1); add(but2); } public void actionPerformed(ActionEvent event){ //store the label of the button pressed in our String variable buttonpressed=event.getActionCommand(); //Display the label of the pressed button in a textarea output.append("You pressed "+buttonpressed+"\n"); }//ends actionPerformed }//end ex73a

built in java method that gets the label of the current button that has been pressed

a string variable

Page 75: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 7-GRAPHICAL USER INTERFACE -BASIC INPUT AND EVENT 60

HANDLING

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 7.3 Mastery Questions

1.Create a program that has 2 textfields with the labels number 1 and number 2. A textarea called Result should be below the textfields. Add in a button called multiply. The user should be able to enter in 2 numbers (can be decimal numbers), and when they press the Button, the result of multiplying the two numbers should appear.

7.4 USING REPAINT() METHOD TO RECALL THE PAINT METHOD; AND THE

UPDATE() METHOD

The repaint() method is used to call up the paint method again. Since the applet is always running while its being displayed, it is useful to know how

to call up the paint method again from another location in the program. This way, you could adjust the coordinates of a shape and then redraw it when a button is pressed.

NOTE: Put the repaint() method call as the last line the actionPerformed() Method. This will make sure the paint method redone after an event has occurred.

The repaint() method creates a sequence looks like this: repaint(); automatically calls up update(Graphics screen); automatically calls up paint(Graphics screen);

The update(Graphics screen) method actually erases all the drawing that has been done on the screen. Then it calls the paint method again, which can draw on the clean, refreshed screen.

Page 76: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 7-GRAPHICAL USER INTERFACE -BASIC INPUT AND EVENT 61

HANDLING

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 7.4A USING REPAINT TO DRAW A SQUARE IN DIFFERENT SPOTS Applet makes the user enter in x and y coordinates. Pressing button draws the square at

the proper coordinates.

import java.awt.*; import java.awt.event.*; public class ex74a extends java.applet.Applet implements ActionListener{ Graphics screen; TextField x,y; Button submit; Label xname,yname; String xword,yword; int xnum,ynum; public void init() { setLayout(null); x=new TextField(5); y=new TextField(5); submit=new Button("Press"); xname=new Label("x"); yname=new Label("y"); xname.setBounds(45,10,10,20); yname.setBounds(180,10,10,20); x.setBounds(60,10,60,20); y.setBounds(190,10,60,20); submit.setBounds(125,40,50,20); submit.addActionListener(this); add(x); add(y); add(xname); add(yname); add(submit); xnum=50; ynum=50; } public void actionPerformed(ActionEvent event) { //this gets the Strings entered into the textfields xword=x.getText(); yword=y.getText(); //this converts the String numbers from textfield into int xnum=Integer.valueOf(xword).intValue(); ynum=Integer.valueOf(yword).intValue(); repaint(); } public void paint(Graphics screen) { screen.setColor(Color.blue); screen.drawRect(xnum,ynum,40,40); } }//ends class ex74a

These next two lines give a starting value for the x, and y numbers so the paint method has some coordinates to use to draw the initial square. If the paint method doesn't have these numbers, then an error will occur

This line draws a rect with the coordinates of the value currently stored in xnum,ynum and with a width of 40 and height of 40

This calls up the paint method. The value of xnum and ynum will be used to draw the new square remember the screen gets cleared because of the invisible but automatic call to the update method

Page 77: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 7-GRAPHICAL USER INTERFACE -BASIC INPUT AND EVENT 62

HANDLING

________________________________________________________________________ Copyright © 2000 Robbie Kailley

CREATING YOUR OWN VERSION OF UPDATE() TO NOT CLEAR THE SCREEN If you do not want to clear the screen when repaint() is called, then you have to adjust

the update() method yourself and add it to your program code. EXAMPLE 7.4B USING OUR OWN UPDATE TO STOP SCREEN FROM CLEARING BETWEEN

REDRAWS Applet is same as example 7.4a except the screen is not refreshed between redraws

import java.awt.*; import java.awt.event.*; public class ex74b extends java.applet.Applet implements ActionListener{ Graphics screen; TextField x,y; Button submit; Label xname,yname; String xword,yword; int xnum,ynum; public void init() { setLayout(null); x=new TextField(5); y=new TextField(5); submit=new Button("Press"); xname=new Label("x"); yname=new Label("y"); xname.setBounds(50,10,5,20); yname.setBounds(185,10,5,20); x.setBounds(60,10,60,20); y.setBounds(190,10,60,20); submit.setBounds(125,40,50,20); submit.addActionListener(this); add(x); add(y); add(xname); add(yname); add(submit); xnum=50; ynum=50; } public void actionPerformed(ActionEvent event) { xword=x.getText(); yword=y.getText(); xnum=Integer.valueOf(xword).intValue(); ynum=Integer.valueOf(yword).intValue(); repaint(); } public void paint(Graphics screen) { screen.setColor(Color.blue); screen.drawRect(xnum,ynum,40,40); } public void update(Graphics screen) { paint(screen); //we call up paint without clearing the screen } }//ends class ex74b

Here is the added update method which doesn't clear the screen

Page 78: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 7-GRAPHICAL USER INTERFACE -BASIC INPUT AND EVENT 63

HANDLING

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 7.4 Mastery Questions

1. Change example 7.4a so you can also adjust the width and height of the square

UNIT EXERCISES

1.Create a program which takes in the name and 4 grades (as percentages) from a user. The computer should output the name followed by an average percentage for the grades entered. 2.Create a program which takes in a users name, the test total, and what mark they actually received on the test. The output should be the name and the percentage achieved on the test. 3.Create a program which lets the user enter in the diameter and the x,y location of a circle. The program should also let the user enter in the RGB color for the shape (a textfield for red, textfield for green, and a textfield for blue) The program should draw the circle (filled in with the proper color) and also output the area of the circle created in a textarea.

Page 79: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 7-GRAPHICAL USER INTERFACE -BASIC INPUT AND EVENT 64

HANDLING

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Page 80: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 8-DECISION STATEMENTS 65

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 8 DECISION STATEMENTS

UNIT OVERVIEW

• 8.1 What is a decision statement and why do we need them?

• 8.2 Basic If..then decision statement

• 8.3 Evaluating Conditions -Relational Operators

• 8.4 Evaluating Multiple Conditions -Logical Operators

• 8.5 Various If..then statements with examples

• 8.6 Checking String Equality

• 8.7 An alternative decision structure: the switch statement

8.1 WHAT IS A DECISION STATEMENT AND WHY DO WE NEED THEM?

In the real world we make decisions all the time. For example, if the traffic light is red we stop, else if it is green we go. As you can see, many of our decisions, when we write them down, start with the word IF. If something is true then I’ll act this way, else if its not then I’ll do something else.

Computers can become very useful, powerful machines if they are able to copy human thinking. Making decisions in a program is one way that computers can copy human thinking.

For example, a program may be used to check to see if a person will get a scholarship based on the average of their grades. A computer can take in all the grades of the student, and calculate the average. Then the computer can make a decision based on the average. The programmer could make it so if the average is greater than 90% then a scholarship is received else no scholarship is received.

8.2 BASIC IF..THEN DECISION STATEMENT

An if..then statement refers to a programming concept which enables computer programs to make decisions. Example: assume we have an integer variable called gradeint, which stores the rounded percentage a student has received in a test.

Steps Example

simple if..then checks to see if the gradeint is greater than 90, and if it is, then print a message

if (gradeint>90 { output.append(”Excellent work”+”\n”); } //ends if

if..then..else is a more complex if then. It does the same as above but will print a special message if the grade is less than 90

if (gradeint>90) { output.append(“Excellent work”+”\n”); } else { output.append(“Nice try”+”\n”); }//ends if

Page 81: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 8-DECISION STATEMENTS 66

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 8.2 A SIMPLE IF..THEN STATEMENT Applet lets user enter in grade; different messages are printed if grade is higher than 90

or if grade is lower than 90

import java.awt.*; import java.awt.event.*; public class ex82 extends java.applet.Applet implements ActionListener{ TextField grade; TextArea output; Button submit; Label entergrade; String gradeword; int gradeint; public void init() { setLayout(null); grade=new TextField(5); output=new TextArea(5,5); submit=new Button("Press"); entergrade=new Label("Enter your grade"); grade.setBounds(100,10,50,20); output.setBounds(50,50,250,150); submit.setBounds(160,10,60,20); entergrade.setBounds(0,10,97,20); submit.addActionListener(this); add(grade); add(output); add(submit); add(entergrade); } public void actionPerformed(ActionEvent event) { gradeword=grade.getText(); gradeint=Integer.valueOf(gradeword).intValue(); if (gradeint>90) { output.setText("Great Job"); } else { output.setText("Better luck next time"); } } //ends the actionPerformed method }//ends class ex82

Here is the if..then statement. The condition being evaluated is if the gradeint is greater than 90. If its true then the first set of brackets is followed, else the second set brackets is followed

Page 82: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 8-DECISION STATEMENTS 67

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 8.2A USING A SIMPLE IF..THEN ELSE TO DETERMINE WHICH OF 2 BUTTONS IS

PRESSED Applet displays different messages in TextArea depending on which button is pressed

import java.awt.*; import java.awt.event.*; public class ex82a extends java.applet.Applet implements ActionListener{ TextArea output; Button but1,but2; String buttonpressed; //stores the label of the button public void init() { output=new TextArea(20,30); add(output); but1=new Button("Button1"); but2=new Button("Button2"); but1.addActionListener(this); but2.addActionListener(this); add(but1); add(but2); } public void actionPerformed(ActionEvent event){ //store the label of the button pressed in our String variable buttonpressed=event.getActionCommand(); //use an if then to determine which button has //been pressed. Display different messages for each button if (buttonpressed.equals("Button1")){ output.append("You pressed Button#1"+"\n");} else if (buttonpressed.equals("Button2")){ output.append("You pressed Button#2"+"\n"); }//ends if statement }//ends actionPerformed }//end ex82a

Section 8.2 Master Questions

1. Change the condition in example 8.2 so the grade must be greater than 95 to get the message “Great Job”. 2. When evaluating a condition, there are only 2 possible outcomes, what are they?

8.3 EVALUATING CONDITIONS -RELATIONAL OPERATORS

Relational operators help evaluate conditions. You may want to see if one number is greater than another number. You may want to see if a number is equal to another number.

this retrieves the label of the button upon which the event occurred. We then store it in our String variable

checking to see which label the String variable is equal to. (More detail in section 8.6)

Page 83: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 8-DECISION STATEMENTS 68

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Table 8.3 Relational Operators Operator Meaning Example

== equals to if (num1==num2) {

!= not equal to if (num1!=num2) {

< less than if (grade<90) {

<= less than or equal to if (salary<=40000) {

> greater than if (SAT>1100) {

>= greater than or equal to if (GPA>=3.5) {

Using relational operators depends on the condition being evaluated. Section 8.3 Mastery Questions

1.What was the relational operator used in example 8.2 program?

8.4 EVALUATING MULTIPLE CONDITIONS -LOGICAL OPERATORS

Quite often in programs, you will want to make decisions based on more than one condition. For example, a scholarship may be decided on GPA and SAT scores. To evaluate multiple conditions we use logical operators.

For example if you wanted the GPA to be greater than 3.5 and SAT to be greater than 1200 you would write: if (GPA>3.5 && SAT>1200) . Table 8.4 Logical Operators Operator Meaning Example

&& and if (GPA>3.5 && SAT>1200) {

|| or if (GPA>3.5 || SAT>1200) {

&& (and) is used when you want both conditions being evaluated to be true in order to perform certain instructions. || (or) is used when you only need on of the two conditions being evaluated to be true in order to perform certain instructions

Page 84: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 8-DECISION STATEMENTS 69

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 8.4 USING RELATIONAL AND LOGICAL OPERATOR && (AND) Applet displays one message if sat>=1000 and grade is >90, if not another message

appears

import java.awt.*; import java.awt.event.*; public class ex84 extends java.applet.Applet implements ActionListener{ TextField grade,sat; TextArea output; Button submit; Label entergrade,entersat; String gradeword,satword; int gradeint,satint; public void init() { setLayout(null); grade=new TextField(5); sat=new TextField(5); output=new TextArea(5,5); submit=new Button("Press"); entersat=new Label("Enter SAT score"); entergrade=new Label("Enter your grade"); grade.setBounds(100,10,50,20); sat.setBounds(275,10,50,20); output.setBounds(50,50,250,150); submit.setBounds(330,10,60,20); entergrade.setBounds(0,10,97,20); entersat.setBounds(180,10,90,20); submit.addActionListener(this); add(grade); add(sat); add(output); add(submit); add(entergrade); add(entersat); } public void actionPerformed(ActionEvent event) { gradeword=grade.getText(); gradeint=Integer.valueOf(gradeword).intValue(); satword=sat.getText(); satint=Integer.valueOf(satword).intValue(); if (gradeint>90 && satint>=1000) { output.setText("Great Job"); } //end of instructions if condition is true else {//if condition is false then this next statement is executed output.setText("Better luck next time"); } //ends if statement } //ends the actionPerformed method }//ends class ex84

Here is the if..then statement. Notice the logical operator &&

Page 85: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 8-DECISION STATEMENTS 70

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 8.4 Mastery Questions

1.What is the output in the TextArea if the following numbers are entered into Example 8.4 (Explain each answer briefly) a)grade: 90 SAT:1000 b)grade: 91 SAT: 1000 c)grade: 90 SAT 1001 d)grade 91 SAT 1001 e)grade 91 SAT 999 f)grade 90 SAT 999 2.In the example program what does the SAT>=1000 mean? How would this change if the statement read SAT>1000? (Hint: try it and see) 3.Change the program ex84 to use the or logical operator (||). What was output during the following conditions? How and why are some of the results different from your answers to number 1? a)grade: 90 SAT:1000 b)grade: 91 SAT: 1000 c)grade: 90 SAT 1001 d)grade 91 SAT 1001 e)grade 91 SAT 999 f)grade 90 SAT 999

8.5 VARIOUS IF..THEN STATEMENTS WITH EXAMPLES

There are many ways to set up if..then statements in a program. The general structure for each different set-up is given below. VARIOUS IF THEN STATEMENT STRUCTURES

Each of the above if..then statements is slightly different than the other. You must decide in a program which of the above is the best type of if..then statement to use in your program. Types 1 , 2 and 3 are fairly straightforward.

if (condition is true) instruction1; else instruction2;

if (condition is true) { instruction1; instruction2; } else if(condition2 is true) { instruction3; instruction4; }

if (condition is true) { instruction1; instruction2; } else { instruction3; instruction4; }

if (condition is true) { instructions; instructions; }

Type1 Type2

Type 4Type3

Page 86: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 8-DECISION STATEMENTS 71

________________________________________________________________________ Copyright © 2000 Robbie Kailley

NESTED IF..THEN STATEMENTS IN DETAIL Type 4 is called a nested if..then statement. What this means is there are many

conditions inside of other conditions. For example, if you are making a program to find the proper letter grade associated

with an entered percentage, there are many choices to be made.

A programmer can try to do it as a type 1,2,or 3 if..then statement but you will be left with something like this: If the grade is greater than 90 then its an A. else, the grade is ????

As you can see, you only have one other option after an A. To make this better, you

should use a nested if..then statement. It would read something like this. if the grade is greater than 90 then its an A else if the grade is greater than 80 then it’s a B else if the grade is greater than 70 then it’s a C+ else if the grade is greater than 60 then it’s a C else if the grade is greater than 50 then it’s a C- else the grade is a F

The nested if..then is like a filter, you only go down to the next level, if the current condition isn’t satisfied.

For example, if the grade entered was a 75. The computer first looks at condition1, it is not met, so next condition2 is examined, it is not met, so condition3 is examined (grade >70) , it is met, therefore the grade is a C+.

You must structure the if..then statement in the proper order otherwise it will not work. For example, if you reversed the order of the conditions,

if the grade is less than 50 then its an F else if the grade is greater than 50 then it’s a C- else if the grade is greater than 60 then it’s a C else if the grade is greater than 70 then it’s a C+ else if the grade is greater than 80 then it’s a B else the grade is an A If you entered the grade 70, the second condition would be met (grade>50), so then the grade give would be a C-. AS SOON AS A CONDITION IS MET, THE CORRESPONDING INSTRUCTION(S) IS FOLLOWED AND THEN THE IF..THEN STRUCTURE IS LEFT. So, in this case, once a condition is met, the letter grade C- is assigned and the if..then structure is left. The other conditions are not evaluated!

Page 87: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 8-DECISION STATEMENTS 72

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Also, be careful of the boundary between conditions. In our statements a grade has to be greater than 90 to get an A. This means that a 90 will be a B. If you want a 90 to be an A, you would have to say in the condition if (grade>=90). EXAMPLE 8.5 NESTED IF..THEN STATEMENT Applet displays the appropriate letter grade associated with an entered percentage

import java.awt.*; import java.awt.event.*; public class ex85 extends java.applet.Applet implements ActionListener{ TextField grade; TextArea output; Button submit; Label entergrade; String gradeword; int gradeint; public void init() { setLayout(null); grade=new TextField(5); output=new TextArea(5,5); submit=new Button("Press"); entergrade=new Label("Enter your grade"); grade.setBounds(100,10,50,20); output.setBounds(50,50,250,150); submit.setBounds(330,10,60,20); entergrade.setBounds(0,10,97,20); submit.addActionListener(this); add(grade); add(output); add(submit); add(entergrade); } public void actionPerformed(ActionEvent event) { gradeword=grade.getText(); gradeint=Integer.valueOf(gradeword).intValue(); //here is the nested if..then statement if (gradeint>90) { output.setText("Your grade is an A"); } else if (gradeint>80) { output.setText("Your grade is a B");} else if (gradeint>70) { output.setText("Your grade is a c+");} else if (gradeint>60) { output.setText("Your grade is a C");} else if (gradeint>50) { output.setText("Your grade is a C-");} else {output.setText("Your grade is an F"); }//end of nested if then } }//ends class ex85

Page 88: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 8-DECISION STATEMENTS 73

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 8.5 Mastery Questions

1. Make a copy of the program and change it so the if..then starts with the F grade and works its way up to the A grade. (Hint. You may need to use multiple conditions and logical operators to make it work)

8.6 CHECKING STRING EQUALITY

If you want to see if a word entered is equal to another word, you have to use a special method.

Example if (answer.equals(“yes”)) { output.setText(“You typed in yes for your answer”); } //ends if

EXAMPLE 8.6 USING STRINGS IN CONDITIONS Applet lets the user enter in a color in a textfield and fills a large square with that color

when a button is pressed

import java.awt.*; import java.awt.event.*; public class ex86 extends java.applet.Applet implements ActionListener{ Graphics screen; TextField color; Button submit; Label entercolor; String colorword; Color clr; //this is a variable of type color it stores different basic Java colors public void init() { setLayout(null); color=new TextField(5); submit=new Button("Submit Color"); entercolor=new Label("Enter red, blue, or green"); color.setBounds(200,10,50,20); submit.setBounds(330,10,80,20); entercolor.setBounds(50,10,150,20); submit.addActionListener(this); add(color); add(submit); add(entercolor); clr=Color.white; } public void actionPerformed(ActionEvent event) { colorword=color.getText(); if (colorword.equals("red")) { clr=Color.red;} else if (colorword.equals("blue")) { clr=Color.blue;} else if (colorword.equals("green")) { clr=Color.green;} else {clr=Color.black; }//ends nested if..then

The init method automatically calls up the paint method once at the beginning of the program. If there is no value for clr the first time paint is run, an error will occur. This lines gives clr a starting value

if the String variable called answer has the same value as the word “yes”, then the condition is true.

Checking what the user entered in the TextField

Program continued on next page �

Page 89: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 8-DECISION STATEMENTS 74

________________________________________________________________________ Copyright © 2000 Robbie Kailley

repaint(); //calls up the paint method,shows new color } public void paint(Graphics screen) { screen.setColor(clr); screen.fillRect(0,0,500,400); }//ends paint method }//ends class ex86

Section 8.6 Mastery Questions

1.Adjust the above program to include another textfield that takes in either the word “top” or the word “bottom”. When the user enters in the value and the button is pressed, the shape moves to either the top or bottom of the applet screen.

8.7 AN ALTERNATIVE DECISION STRUCTURE: THE SWITCH STATEMENT

Another way to make decisions in your programs is to use the switch statement.

NOTE:You can only use switch statements if the condition being checked involves an integer or a character.

Here is a nested if statement: if (accident==0) insurance=1300;

else if (accident==1) insurance=1500;

else if (accident==2) insurance=1700;

else insurance=2000; You could have used a switch statement to perform the same function:

Example switch(accident) { //this says, lets check the value of accident

case 0: //if the value of accident is 0 perform the proper instructions insurance=1300; break;//this tells the program to skip all the rest of the case statements case 1: //You NEED to put the break insurance=1500; //statements in order to leave the switch statement once break; //a case statement has been done. case 2: insurance=1700; break; default: //the default is performed if none of the case statements insurance=2000; //were true }//ends switch statement

Note: You cannot use switch statements to check things that have an upper or lower limit. For example, you cannot use the switch statement to check if a grade is between 80 and 90. You can only check for one value at a time. This is called checking for discrete values.

Page 90: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 8-DECISION STATEMENTS 75

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 8.7 USING A SWITCH STATEMENT Applet will do the same thing as example 8.6 except it uses a switch statement to make

decisions

import java.awt.*; import java.awt.event.*; public class ex87 extends java.applet.Applet implements ActionListener { Graphics screen; TextField color; Button submit; Label entercolor; String colorword; //this is to get the String the person typed in int colorint; //this is to store the number when converting the String Color clr; //this is a variable of type color it stores different basic Java colors public void init() { setLayout(null); color=new TextField(5); submit=new Button("Submit Color"); entercolor=new Label("Enter 1 for red, 2 for blue, or 3 for green"); color.setBounds(250,10,50,20); submit.setBounds(330,10,80,20); entercolor.setBounds(0,10,240,20); submit.addActionListener(this); add(color); add(submit); add(entercolor); clr=Color.white; } public void actionPerformed(ActionEvent event) { colorword=color.getText();//get the String from textfield colorint=Integer.valueOf(colorword).intValue(); switch (colorint) { //begin switch statement case 1: clr=Color.red; //assigning the color red if 1 is entered break; case 2: clr=Color.blue; break; case 3: clr=Color.green; break; default: //if any other number,the color is black clr=Color.black; }//ends switch statement repaint(); //calls up the paint method again } public void paint(Graphics screen) { screen.setColor(clr); //sets color to current clr variable value screen.fillRect(0,0,500,400);//fill in a rectangle using the color specified above }//ends paint method }//ends class ex87

Page 91: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 8-DECISION STATEMENTS 76

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 8.7 Mastery Questions

1.Using a switch statement, create a simple program that requests the user for what type of shape they want (i.e. enter 1 for square, 2 for oval , 3 for rectangle etc..). Then it draws out the shape (preset size). The starting default shape the user sees is a square, the other shapes are oval, circle and rectangle.

UNIT EXERCISES

1. Create 2 textfields, one which has the label “Color” and the other “Shape”. The user should be able to enter in the basic colors such as red,blue and green into the Color texfield. The user should be able to enter in a shape “Rectangle”,”Oval” into the shapes textfield. Then when the user clicks on the submit button, the proper shape filled with the proper color shows up in the middle of the applet. 2. Create an applet which has 3 textfields with the following labels: Hemoglobin, Mean Cell Volume (MCV), and Ferritin The applet should also have a button called “Complete diagnosis”. The applet should also have an output textfield underneath the button. If the Hemoglobin < 115 and the MCV <80 and the ferritin<20 the message “This patient has iron deficiency “ should appear in textarea. If the hemoglobin<115 and the MCV <80 and the ferritin>100 then the message “This patient has anemia chronic disease” should appear in the textarea. For any other combination of numbers the message “This patient is not having any iron related problems” should appear in the textarea.

Hemoglobin

Ferritin

Mean Cell Volume

Complete Diagnosis

Page 92: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 9-GUI COMPONENTS: DROP MENUS,CHECKBOXES,SCROLLBARS 77

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 9 GUI COMPONENTS:DROP MENUS,CHECKBOXES,SCROLLBARS

UNIT OVERVIEW

• 9.1 Declaring and Using Drop Menus

• 9.2 Declaring and Using Checkboxes

• 9.3 Declaring and Using Checkboxgroups

• 9.4 Declaring and Using Scrollbars

9.1 DECLARING AND USING DROP MENUS

As was seen in the last unit, you can prompt the user to enter in an number and then press the submit button to make something happen, based on what choice the user entered. There is another way to let the user select a preset number of choices. It is called a drop menu (sometimes called a drop down menu). Creating a drop down menu involves a number of steps. It is a component like textfields, but there are a few extra steps that need to be followed. Table 9.1 Steps in Creating Menubars Steps Example

add import line import java.awt.event.*;

add the interface ItemListener to program heading line

public class example extends java.applet.Applet implements ItemListener

declare the menubar variable as of type Choice

Choice mymenubar;

initialize the menu bar mymenubar=new Choice();

add the menu items mymenubar.add(“Red”); mymenubar.add(“Blue”);

add the listener to the menu bar mymenubar.addItemListener(this);

add the menu bar to your applet

add(mymenubar);

add the method itemStateChanged() In this method you can put the instructions for what to do when the menu bar is selected. You could also call up other methods from inside this method, which contain further instructions.

public void itemStateChanged(ItemEvent event) { repaint(); }

Use the method mymenubar.getSelectedItem() to get the menubar item that is currently selected (as a String).

menuitem=mymenubar.getSelectedItem();

ItemEvent is a variable which stores information about the menu bar currently in use, the name of the labels, the name of the selected label etc…

menuitem is a string variable which will store the label of the currently selected menubar choice

Page 93: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 9-GUI COMPONENTS: DROP MENUS,CHECKBOXES,SCROLLBARS 78

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 9.1 CREATING A SIMPLE DROP DOWN MENU Applet lets a user choose a color from a menu and fills a rectangle with that color

import java.awt.*; import java.awt.event.*; public class ex91 extends java.applet.Applet implements ItemListener{ Graphics screen; Choice mymenubar;//menubar variable Color clr; String menuitem;//holds the current value of selected menu //item public void init() { mymenubar=new Choice(); //initializes the new menubar mymenubar.addItem("Red");//adds the items to menu mymenubar.addItem("Blue"); mymenubar.addItem("Green"); mymenubar.addItemListener(this);//adds listener to menu add(mymenubar); //adds menu bar to the applet clr=Color.white; //initial value for clr variable } public void itemStateChanged(ItemEvent event) { menuitem=mymenubar.getSelectedItem(); //gets the name of the current selected //menu item /*use a nested if then to determine the clr variable value based on the menuitem selected. The names of the menuitems are determined in the init method when you create the menubar*/ if (menuitem.equals("Red")){ clr=Color.red;} else if (menuitem.equals("Blue")){ clr=Color.blue;} else if (menuitem.equals("Green")){ clr=Color.green; }//ends if repaint(); //calls up the paint method again } //ends itemStateChanged Method public void paint(Graphics screen) { screen.setColor(clr); screen.fillRect(0,0,500,400); } } //ends ex91

Page 94: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 9-GUI COMPONENTS: DROP MENUS,CHECKBOXES,SCROLLBARS 79

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 9.1 Mastery Questions

1. Adjust the program ex91 so that you can choose 3 other basic java colors

9.2 DECLARING AND USING CHECKBOXES

CheckBoxes let the user select items, by clicking in boxes. If the box is chosen, then a checkmark appears in it. Otherwise the box remains blank. Using checkboxes involves all the basic steps as declaring and using other components. Table 9.2 Steps in Creating ChekBoxes Steps Example

add the import line import java.awt.event.*;

add the interface ItemListener to program heading line

public class ex92 extends java.applet.Applet implements ItemListener{

declare the checkbox item as type Checkbox

Checkbox mybox;

initialize the Checkbox

mybox=new Checkbox(“Tax”,null,false);

add the listener to the Checkbox mybox.addItemListener(this);

add the Checkbox to your applet add(mybox);

add the method itemStateChanged(ItemEvent event) in this method you can put the instructions for what to do when the Checkbox is selected.

public void itemStateChanged(ItemEvent event) {

Handling Checkboxes in Programs: The common methods for the checkboxes are: mybox.getLabel(); mybox.getState(); mybox.setLabel(); mybox.setState();

if (mybox1.getState()==true) {clr=Color.red;} if (mybox2.getState()==true) {clr=Color.blue;} if (mybox3.getState()==true) {clr=Color.green;}

“ Tax” is the text string for the checkboxes label null : checks if the checkbox a part of group? (value can be null or true) false : is a boolean indicating whether this checkbox is selected

ItemEvent is a variable which stores information about the checkbox currently in use, the name of the labels, the name of the selected label etc…

set the current state of the textbox (true

or false)

set the textlabel of the textbox

returns the checkbox state (true if its selected, false if its not)

returns the Label of the CheckBox

Page 95: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 9-GUI COMPONENTS: DROP MENUS,CHECKBOXES,SCROLLBARS 80

________________________________________________________________________ Copyright © 2000 Robbie Kailley

NOTE: The next example will have some flaws in it. They are left there on purpose, to show you why checkbox groups are important. This is discussed in the next section.

EXAMPLE 9.2 SIMPLE CHECKBOX EXAMPLE Applet lets user click on a checkbox to determine the color of the painted rectangle

import java.awt.*; import java.awt.event.*; public class ex92 extends java.applet.Applet implements ItemListener{ Graphics screen; Checkbox mybox1,mybox2,mybox3; //checkboxes variable Color clr; public void init() { mybox1=new Checkbox("Red",null,false); //initializes the checkboxes mybox2=new Checkbox("Blue",null,false);// mybox3=new Checkbox("Green",null,false);//all start unchecked mybox1.addItemListener(this); //adds a listener mybox2.addItemListener(this); //adds a listener mybox3.addItemListener(this); //adds a listener add(mybox1); //add the checkboxes to the applet add(mybox2); add(mybox3); clr=Color.white; //initial value for clr variable } public void itemStateChanged(ItemEvent event) { //the if checks to see if the checkbox has been clicked. If it //is selected, then getstate is true, then we will change the //color accordingly if (mybox1.getState()==true) {clr=Color.red;} if (mybox2.getState()==true) {clr=Color.blue;} if (mybox3.getState()==true) {clr=Color.green;} repaint(); //calls up the paint method again, so new color is shown } //ends itemStateChanged Method public void paint(Graphics screen) { screen.setColor(clr); screen.fillRect(0,0,500,400); } } //ends ex92

Section 9.2 Mastery Questions

1.Add 2 more checkboxes to the applet, yellow and pink. Make them work. 2.What is the flaw in the program (hint, try to select more than 1 checkbox and see what happens)

9.3 DECLARING AND USING CHECKBOX GROUPS

In the last section, there was a problem when selecting more than 1 checkbox. It is possible to make a number of checkboxes members of the same group, so that only one of them may be checked at a time. When checkboxes are members of a group, their shape changes from square to round.(type in the sample program to see this)

Page 96: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 9-GUI COMPONENTS: DROP MENUS,CHECKBOXES,SCROLLBARS 81

________________________________________________________________________ Copyright © 2000 Robbie Kailley

The steps of declaring the checkboxes of part of a group are quite similar to what we did in the previous section with some small adjustments. Table 9.3 Steps in using Checkboxgroups Steps Example

you must declare a variable called CheckboxGroup

CheckboxGroup mygroup;

you must initialize the CheckboxGroup

mygroup=new CheckboxGroup();

you must adjust the initializing of the Checkboxes to indicate they belong to mygroup.

mybox1=new Checkbox(“Red”,mygroup,false); mybox2=new Checkbox(“Blue”,mygroup,false);

everything else stays the same as when dealing with checkboxes (section 9.2)

EXAMPLE 9.3 USING CHECKBOXGROUP Applet uses a checkboxgroup to let the user only select one checkbox at a time

import java.awt.*; import java.awt.event.*; public class ex93 extends java.applet.Applet implements ItemListener{ Graphics screen; Checkbox mybox1,mybox2,mybox3; //checkboxes variable CheckboxGroup mygroup; //this declares a checkboxgroup Color clr; public void init() { mygroup=new CheckboxGroup(); //initializes the new checkboxgroup mybox1=new Checkbox("Red",mygroup,false); //initializes the checkboxes mybox2=new Checkbox("Blue",mygroup,false); mybox3=new Checkbox("Green",mygroup,false); mybox1.addItemListener(this); //adds a listener to checkbox mybox2.addItemListener(this); //adds a listener to checkbox mybox3.addItemListener(this); //adds a listener to checkbox add(mybox1); //add the checkboxes to the applet add(mybox2); add(mybox3); clr=Color.white; //initial value for clr variable } public void itemStateChanged(ItemEvent event) { //the if checks to see if the checkbox has been clicked. If it is selected, then getstate is true, then //we will change thecolor accordingly if (mybox1.getState()==true) {clr=Color.red;} if (mybox2.getState()==true) {clr=Color.blue;} if (mybox3.getState()==true) {clr=Color.green;} repaint(); //calls up the paint method again, so new color is shown } //ends itemStateChanged Method public void paint(Graphics screen) { screen.setColor(clr); screen.fillRect(0,0,500,400); } } //ends ex93

indicates the checkboxes belong to mygroup

we have put in “mygroup” in the initializing of the checkboxes, indicating it’s a member of that checkboxgroup

Page 97: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 9-GUI COMPONENTS: DROP MENUS,CHECKBOXES,SCROLLBARS 82

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 9.3 Mastery Questions

1.Create a program that has 3 checkboxes, square,oval,circle. They should be a part of a checkboxgroup. When the user clicks on one of them, then a preset shape shows up on the middle of the applet screen.

9.4 DECLARING AND USING SCROLLBARS

Sometimes in programs, scrollbars can be very useful. If you want the user to be able to select from a wide range of values or if you want to display large amounts of information which the user must choose from, a scrollbar is the component to use. Table 9.4 Using ScrollBars Steps Example

add import event line import java.awt.event.*;

add the interface AdjustmentListener to program heading line

public class ex94 extends java.applet.Applet implements AdjustmentListener {

declare the Scrollbar variable as of type Scrollbar

Scrollbar myscroll;

initialize the Scrollbar myscroll=new ScrollBar(0,50,10,0,100);

add the listener to the Scrollbar myscroll.addAdjustmentListener(this);

add the Scrollbar to your applet add(myscroll);

add the method adjustmentValueChanged(AdjustmentEvent event) . In this method you can put the instructions for what to do when the Scrollbar is selected.

public void adjustmentValueChanged(AdjustmentEvent event) {

use common scrollbar methods width=myscroll.getValue() ;

Value: this is the scroller’s starting value.

Maximum

minimum

Orientation: this scrollbar’s orientation is HORIZONTAL

scrollers size

orientation: can be either 0 (horizontal) or 1 (vertical)

value: the starting position of the scroller

size: the scrollers visible size on the applet

minimum and maximum values for the endpoints of the scrollbar:

AdjustmentEvent is a variable which stores information about the Scrollbar in use.

this gets the current integer value of where the scroller is

Page 98: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 9-GUI COMPONENTS: DROP MENUS,CHECKBOXES,SCROLLBARS 83

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 9.4 SIMPLE SCROLLBAR EXAMPLE Applet adjusts the width of the drawn rectangle when the scrollbar is moved

import java.awt.*; import java.awt.event.*; public class ex94 extends java.applet.Applet implements AdjustmentListener{ Graphics screen; Scrollbar size; int width; public void init() { setLayout(null); size=new Scrollbar(0,50,1,0,100);//initializing the scrollbar size.addAdjustmentListener(this); size.setBounds(100,10,100,20); //resizing the scrollbar add(size); width=50; //starting width of rectangle } public void adjustmentValueChanged(AdjustmentEvent event) { width=size.getValue(); repaint(); } public void paint(Graphics screen) { screen.setColor(Color.blue); screen.drawRect(100,100,width,50); }//ends paint method }//ends ex94

It is possible to add more than 1 type of listener to an applet. For example, you may want to have buttons and a scrollbar in an applet. All you need to do is implement the proper methods that we have already gone through in this unit. The program heading line must implement the desired

types of listeners separated by commas. EXAMPLE 9.4B SCROLLBARS AND BUTTONS IN AN APPLET, WITH LISTENERS ON BOTH. Applet adjust ex 9.4, with 2 buttons which change the color of the square.

import java.awt.*; import java.awt.event.*; public class ex94b extends java.applet.Applet implements AdjustmentListener,ActionListener{ Graphics screen; Scrollbar size; int width; Button red,blue; String buttonpressed; Color clr; public void init() { setLayout(null); size=new Scrollbar(0,50,1,0,100);//initializing the scrollbar size.addAdjustmentListener(this); size.setBounds(100,10,100,20); //resizing the scrollbar add(size); red=new Button("Red")); red.addActionListener(this); red.setBounds(210,10,80,30); add(red);

This gets the current value of the scroller on the scrollbar. We assign that value to a variable called width. The width variable is used to draw the square

we are using buttons and scrollbars so we implement 2 different types of listeners in the program heading line,separated by a comma

Program continued on next page �

Page 99: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 9-GUI COMPONENTS: DROP MENUS,CHECKBOXES,SCROLLBARS 84

________________________________________________________________________ Copyright © 2000 Robbie Kailley

blue=new Button("Blue"); blue.addActionListener(this); blue.setBounds(300,10,80,30); add(blue); width=50; //starting width of rectangle clr=Color.blue; //gives starting value for color } public void adjustmentValueChanged(AdjustmentEvent event) { width=size.getValue(); repaint(); } public void actionPerformed(ActionEvent event){ buttonpressed=event.getActionCommand(); if (buttonpressed.equals("Red")){ clr=Color.red; } if (buttonpressed.equals("Blue")){ clr=Color.blue; } repaint(); }//ends actionperformed public void paint(Graphics screen) { screen.setColor(clr); screen.drawRect(100,100,width,50); }//ends paint method }//ends ex94b

Section 9.4 Mastery Questions

1.Adjust the applet ex94 so the scrollbar is vertical, and so the shape is being move up or down according to the scrollers position. (Do not resize the shape, only move it up or down)

UNIT EXERCISES 1.Create a program which lets a person draw a face: (Remember to create your own methods and call them up in the appropriate spots to help organize your program) The program should have:

• A drop menu to choose the shape of the head (oval,circle,square,rectangle)-preset sizes

• A drop menu to choose the shape of the eyes (square or oval)-preset sizes

• The applet should also have 2 checkboxes for determining if the eyes are to be Filled or framed.

• There should be a checkbox group for determining the color of the eyes. (have 3 choices)

• A scrollbar should be placed on the window which makes the nose move up or down.

• Another scrollbar controls whether the eyes move further apart or closer together

since we implemented ActionListener and an AdjustementListener, we must include the proper methods for both. The actionPerformed is for the ActionListener, and the adjustmentValueChanged is for the AdjustmentListener.

Page 100: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 10-LOOPS 85

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 10- LOOPS

UNIT OVERVIEW

• 10.1 What are loops and why use them?

• 10.2 For Loops and simple method creation

• 10.3 Simple Animation using For Loops

• 10.4 While Loops

• 10.5 Do While Loops

• 10.6 Creating Random Numbers

10.1 WHAT ARE LOOPS AND WHY USE THEM?

Loops are programming structures that let you repeat a series of instructions over and over again until they are told to stop. Loops can be very useful because they can add animation to your program by repeating a series of drawing instructions with different coordinates each time. Loops can also help filter through large amounts of information if you are looking for a specific piece of information. For example, loops can help you find the sum of all the numbers from 1 to 100 quickly. Anytime you find yourself repeating a set of instructions, you know a loop should be used. A common term for referring to a repetition of instructions is an iteration. This just means how many times the loop has repeated so far.

10.2 FOR LOOPS

A for loop is a definite loop. This means that you know exactly how many times you want to repeat a series of instructions when you create it. Only use it in instances when you know the number of repetitions required. An example of such a time is when you want to add up all the numbers from 1 to 10. Example: for (int counter=0;counter<10;counter=counter+1) { output.setText(“This is still looping”); }//ends for loop Initialization-Creating the integer variable used to keep track of how many times the loop has been done Condition-The condition of repetition is that counter must be less than 10. (counter<10). While counter is less than 10 we keep looping. This specifies a condition to check each time before the loop is done. If the condition is true, keep doing the loop

When the condition becomes false, stop doing the loop Increment-This specifies how fast to increase the integer variable towards the ending condition. The increment ensures that each time the loop is executed, we increase the value of counter by 1. So, we say counter is equal to what counter used to be, plus 1 (counter=counter+1) So, if counter used to be zero, now it will be 1. If counter used to be 1, now it will be 2 etc…

Initialization:

Condition Increment

Page 101: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 10-LOOPS 86

________________________________________________________________________ Copyright © 2000 Robbie Kailley

NOTE: The increment is very important, it should bring the loop closer to the ending condition all the time. Otherwise the loop will never end.

USING YOUR OWN METHODS We have already covered how to create and use your own methods when drawing

shapes. You can also create methods that don’t have drawing instructions. For more information on methods, go to the method interlude unit.

Example public void myloop() { instructions; instructions; } //ends the method To call up myloop inside one of the base java methods (init, adjustmentVaueChanged, etc..) you would place the following line inside the base java method: myloop(); //this tells the computer to find myloop() method and execute the //the instructions inside of it

NOTE: You can create and call up as many methods as you want. In fact you can even call up a made up method inside of another made up method.

EXAMPLE 10.2A SIMPLE FOR LOOP WITH A METHOD CALL IN INIT() METHOD Applet prints out a message several times using a for loop

import java.awt.*; public class ex102a extends java.applet.Applet { int counter; String message; TextArea output; public void init() { output=new TextArea(10,30); add(output); message= "This is one iteration"; doloop(); //this calls up doloop method } public void doloop() { for (int counter=1;counter<10;counter=counter+1) { output.append(message+"\n"); }//ends for loop }//ends doloop method }//ends class 102a

the empty round braces indicate this method doesn’t need any special variables sent to it (unlike the graphics methods which needs the Graphics screen variable sent to it)

public means that this method can be called from any other method in the program. Void means that this method doesn’t return any value to the method that called it (this is advanced and dealt with in the method interlude unit).

Page 102: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 10-LOOPS 87

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 10.2B MATH EXAMPLE USING A FOR LOOP Applet prints out a times table for the number 7

import java.awt.*; public class ex102b extends java.applet.Applet { int counter; int total; TextArea output; public void init() { output=new TextArea(10,30); add(output); doloop(); //this calls up doloop method }//ends init public void doloop() { for (int counter=1;counter<10;counter=counter+1) { total=counter*7; output.append(""+7+"*"+counter+"="+total+"\n"); }//ends for loop }//ends doloop method }//ends class 102b

Section 10.2 Mastery Questions

1. Adjust program 10.2b so that a person can enter what number they want to multiply by. Then the applet will display the results. For example, if the person chose 3, then the applet would output 3*1=3, 3*2=6,3*3=9 etc… all the way up to 3*10=30. 2.Adjust the program you made in question #1, so that the total sum of all the multiplication’s will also be output. (This should be done as a calculation inside the for loop). (hint. Use a variable to keep track of the sum, and keep adjusting the variable at the end of each iteration)

10.3 SIMPLE ANIMATION USING FOR LOOPS

Note: For the animation applets in this section, run the applets in the appletviewer. Web browsers do not run the empty for..loop appropriately. The best way to do animations is shown in Unit 16.

To create simple animation in a program, you must follow the basic steps: 1. draw the object 2. let the person see the object (create a small delay) 3. erase the object 4. change the coordinates of the object 5. repeat steps 1 to 4 over and over again.

This next line takes the current counter and times it by 7

This line combines text and numbers to produce the output

Page 103: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 10-LOOPS 88

________________________________________________________________________ Copyright © 2000 Robbie Kailley

CREATING DELAYS We can create simple animation using for loops but there will be a definite number of times

the animation will occur. This can be a disadvantage at times, but you can use advanced animation techniques to avoid this (Unit 16). There is flexibility as to how a programmer can choose to create a small delay. In Unit 16 of this book, a method using a built in java class called Thread is shown.

However, you can use an empty for loop to create a delay. The computer will stay in the

for loop until the condition is met. Therefore, you must play around with your specific

computer to determine how large to make your ending condition.

Example for (int counter=1;counter<10000;counter=counter+1) { } This loop executes no instructions, but it takes time for the computer to repeat the loop so

many times. This is what creates the delay for the animation.

ERASING THE OBJECT There are two common ways to erase an object.

1.redraw the object in the same color as the current background 2.draw the whole background again, which would essentially refresh the background, erasing any current object which were on it. The method that you use may depend on the specific program you are creating. Sometimes it is good to try both ways and see which way looks better. REDUCING FLICKER

Your animation will flicker (considerably depending on the computer you are using). To reduce your flicker: 1.Try the 2 different erasing methods mentioned above. One may look better 2. Reduce the amount of delay (in the empty for loop) 3. Use double buffering (an advanced, but most effective method, shown in unit 16) EXAMPLE 10.3A ANIMATION BY DRAWING OBJECT SAME AS BACKGROUND COLOR Applet shows a blue square moving across the screen.(View in appletviewer)

import java.awt.*; public class ex103a extends java.applet.Applet { Graphics screen; int x; public void init() { x=5; //the starting x value for the square }//ends init public void paint(Graphics screen) { for (int count=1;count<100;count=count+1) { screen.setColor(Color.blue); screen.drawRect(x,10,30,30); /*this next for loop is a dummy for loop which doesn't have any instructions to execute, it just takes time for the program to count up to 60000, which creates the delay necessary for animation,you may have to

adjust that number depending on your computers speed*/ for (int dummy=1;dummy<60000;dummy=dummy+1) { } screen.setColor(Color.white); //set to background color screen.drawRect(x,10,30,30);//draw rect in background color x=x+1;//before repeating loop, change x to new value of x+1 }//ends outer for loop }//ends paint method }//ends class 103a

3.dummy for loop, creates delay

2.draw shape

1. loop for animation.Repeat steps 100 times

4.erasing and moving the coordinates

Page 104: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 10-LOOPS 89

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 10.3B ANIMATION BY REDRAWING THE WHOLE BACKGROUND Applet shows a blue square moving across the screen. (View in appletviewer)

import java.awt.*; public class ex103b extends java.applet.Applet { Graphics screen; int x; public void init() { x=5; //the starting x value for the square }//ends init public void paint(Graphics screen) { for (int count=1;count<100;count=count+1) {//repeat 100 times screen.setColor(Color.blue); screen.drawRect(x,10,30,30); //this next for loop is a dummy for loop which doesn't //have any instructions to execute, it just takes time //for the program to count up to 60000, which creates //the delay necessary for animation,you may have to //adjust that number depending on your computers speed for (int dummy=1;dummy<60000;dummy=dummy+1) { } screen.setColor(Color.white); //set to background color screen.fillRect(0,0,500,400);//fill in the whole background x=x+1;//before repeating loop, change x to new value of x+1 }//ends outer for loop }//ends paint method }//ends class 103b

Section 10.3 Mastery Questions

1.Adjust the Example 10.3a so that the square moves further across the screen. 2.Adjust the program you created in question #3 so the square moves down the screen, and when it reaches the 300 pixel level, a message appears, saying “Near the bottom of the applet”. (Hint:You will need to use an if then to check the value of the squares height)

10.4 WHILE LOOPS

These are a little more flexible than for loops. While loops can be definite loops, but they can also be indefinite loops. This means that you may not be sure how many times the statements will be repeated but you know under what condition the loop would stop. That condition will be reached sometime, when the user performs a certain action.

NOTE: When using while loops, make sure you change the conditional variable inside the body of the loop so it moves closer towards termination.

Page 105: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 10-LOOPS 90

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Example cards=1; while (cards<10) { dealcard(); cards=cards+1; }

EXAMPLE 10.4A USING A SIMPLE WHILE LOOP Applet prints a message several times using a while loop

import java.awt.*; public class ex104a extends java.applet.Applet { int counter; String message; TextArea output; public void init() { message="This is an iteration of a while loop"; output=new TextArea(20,40); add(output); do_while_loop(); //calls the method with the while loop } public void do_while_loop() { counter=1; while (counter<=10) { output.append("This is the "+counter+"iteration"+"\n"); counter=counter+1; } //ends while loop }//ends do_while_loop method }//ends class 104a

USING A LARGE WHILE LOOP FOR ANIMATION

To create a large while loop, you set a condition that takes a lot of time to become false. How large the number is depends on your computer, play around with the example 10.4b to find out a good number for your computer. **You still need to use an empty for loop to create a delay.**

initialization of conditional variable

the condition to be tested. While the condition is true the loop is repeated.

manually changing the conditional variable so its getting closer to making the testing condition not true. Whatever card used to be, now its value is 1 more. Then the program goes back up to the condition, tests it and determines whether to repeat again.

calling a dealcard method

the conditional variable

condition of looping

adjusting conditional variable, brings loop closer to termination

Page 106: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 10-LOOPS 91

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 10.4B USING A LARGE WHILE LOOP FOR ANIMATION Applet draws a rectangle moving across using a while loop.(View in appletviewer)

import java.awt.*; import java.awt.event.*; public class ex104b extends java.applet.Applet{ Graphics screen; int x,move,running; public void init() { x=0; move=1; running=1; //initialize the conditional variable } public void paint(Graphics screen) { while (running<1000) { screen.setColor(Color.red); screen.fillRect(x,30,50,50); for(int counter=1;counter<60000;counter=counter+1) {} screen.setColor(Color.white); screen.fillRect(x,30,50,50); if (x>350) { move=move*-1; } x=x+move; running=running+1; } } }//ends class 104b

Section 10.4 Mastery Questions

1. Adjust example 10.4b so that the box bounces back and forth a few times across the screen. 2.Adjust the program made in number 1, so the box seems to move faster across the screen. ***Do not change the for loop condition, there is another way*** 3.Redo Mastery Question #1 from section 10.2, except use a while loop.

10.5 DO WHILE LOOPS:

Do while loops are similar to while loops except the statements in the loop have to be run at least once. In a while loop, the condition is tested at the top of the loop, so if the condition is false right away, then the loop instructions are never executed. In a do while loop, the condition is tested at the bottom, so the loop instructions must be executed at least once before there is a possibility of termination.

the x variable is the current x position of the square

move is the amount the square is moved each loop iteration

the if then checks if the current x position is 350 pixels, if it is, change the move variable to the opposite direction.

increments the conditional variable closer to condition of termination

adjust the x value by x+move

dummy for-loop,creates a delay

the while loop keeps the animation going if the red box doesn't make it to the far right side of your screen and bounce back, then increase the number limit in the condition from 1000 to something larger.Recompile and run again

Page 107: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 10-LOOPS 92

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Example card=1; do { output.setText(“You have”+card+”total cards”); card=card+1; } while (card<10);

This executes at least once and evaluates the condition at the bottom of the loop

EXAMPLE 10.5 A DO WHILE LOOP Applet prints out a message several times using a do..while loop

import java.awt.*; public class ex105 extends java.applet.Applet { int counter; TextArea output; public void init() { output=new TextArea(20,40); add(output); do_loop(); } public void do_loop() { counter=1; do { print_message(); counter=counter+1; }while (counter<=10); }//ends do_loop public void print_message() { output.append("This is the "+counter+" iteration"+"\n"); }//ends print_message }//ends ex105

Section 10.5 Mastery Questions

1.Redo Section 10.2 Mastery question #1 using a do..while loop.

SECTION 10.6 CREATING RANDOM NUMBERS

Random numbers are very useful in many circumstances. Creating dice or card games involves random numbers. Anytime you want a random selection made in a program, a random number is the way to do it.

evaluation of condition is at the bottom of the loop

initializing the condition variable so it has a starting value

changing the condition variable inside the loop

calling method do_loop

calls method print message inside of the loop, the loop keeps executing while counter<=10

increasing conditional variable

Page 108: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 10-LOOPS 93

________________________________________________________________________ Copyright © 2000 Robbie Kailley

The built in Java random function creates a random decimal number between 0.0 and 1.0. You have to adjust the random number created to the size you want it to be. Also, if you want the random number to be an integer, you have to CAST the generated random number into an integer.(for more on casting see unit 5, section 5.6) Table 10.6 Creating Random Numbers Steps Example

Declare the variable int randominteger or double randomdouble

Create the random number, as an integer between 0-100

randominteger =(int)(100*Math.random());

or, you can create the random number,as an integer between 0-1000

randominteger =(int)(1000*Math.random());

You can also create the random number as a decimal number between 0-1000

randominteger =(1000*Math.random());

EXAMPLE 10.6A RANDOM NUMBER GENERATION AS INTEGERS Applet display several (integer) random numbers in a list on the screen.

import java.awt.*; public class ex106a extends java.applet.Applet { int counter,randominteger; TextArea output; public void init() { output=new TextArea(20,40); add(output); do_loop(); } public void do_loop() { counter=1; while (counter<=10){ randominteger=(int)(100*Math.random()); output.append("This is the random number"+randominteger+"\n"); counter=counter+1; } }//ends do_loop }//ends ex106a

When generating random numbers as decimals, controlling the number of decimal

places created is suprisingly difficult in Java. Since most programs do not involve creating random decimal numbers, example have no indication of how to control the decimal places. If you are interested in this, look up NumberFormat class in the Java api, or go to my website http://www3.telus.net/javastarter and go to the download page.

put in the upper limit of the random number you want to generate and multiply it by Math.random()

Page 109: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 10-LOOPS 94

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 10.6B RANDOM NUMBER GENERATION AS DECIMALS Applet displays a list of decimal random numbers

import java.awt.*; public class ex106b extends java.applet.Applet { int counter; double randomdouble; TextArea output; public void init() { output=new TextArea(20,40); add(output); do_loop(); } public void do_loop() { counter=1; while (counter<=10){ randomdouble=(100*Math.random()); output.append("This is the random number"+randomdouble+"\n"); counter=counter+1; } }//ends do_loop }//ends ex106b

Section 10.6 Mastery Questions

1. Adjust example 10.6a so that it prints out a series of random numbers between 1-6.

UNIT EXERCISES

(View exercise #3 in the appletviewer) 1. Use a for loop to calculate the sum of all the numbers between two numbers entered by a user. The sum should be output in a TextArea. 2.Use a while loop to print out all the numbers divisible by 4 between 1 and 50. 3.Use a large while loop to get a square to start moving from the middle of the screen, diagonally towards one of the walls. Make it so the square keeps bouncing off all the walls.(Hint: use if then statements to check position of the square and adjust the motion appropriately) 4.Create a simple game of dice, where the person enters in their guess of what the roll of two dice will be. Their choices are under seven, seven, and over seven. The choice should be in the form of a checkboxgroup. Then have a button that says roll dice. When the button is clicked, the resulting number is printed in large red letters using drawString. Also, whether person guessed right or not should be printed. Your screen should look like this:

ROLL DICE The Roll was 12

You Lost under 7 7 over 7

Page 110: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 11-IMPORTING IMAGES AND SOUNDS 95

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 11 IMPORTING IMAGES AND SOUNDS

UNIT OVERVIEW

• 11.1 How pictures are used in Java

• 11.2 Basic Steps in using images in your program

• 11.3 How sounds are used in Java

• 11.4 Basic Steps in using sounds in your program

11.1 HOW PICTURES ARE USED IN JAVA

Pictures are stored using a special format on the Internet. In Java there are 2 basic picture formats used: GIF (Graphics Interchange Format) and JPEG. So, when you create images on your own using a paint program, make sure you have the option of saving the image as a GIF or JPEG. Also, when you copy images from the Internet (make sure the author gives you permission), you should see the extension as being GIF or JPEG (another way JPEG extensions are written is JPG). If it isn’t, use a program to convert to one of these two types of files. Images can get very large in memory size. Try to keep your image files to a small size. If your program compiles correctly but still doesn’t work, try using a smaller picture to see if it helps.

Some example image names could be: basketball.Gif Lincon.Jpg

11.2 BASIC STEPS IN USING IMAGES IN YOUR PROGRAM

Table 11.2 Basic Steps in Using Images in your program Step Example

Make sure you have the picture saved in GIF or JPG format

Make sure the picture file is in the same folder as your Java Program Code

Create the Image variable to hold the picture

Image mypicture;

Initialize the image so it is ready to load. Do this in the init method

mypicture=getImage(getCodeBase(),"happy.gif");

Show the picture on the applet display. Do this in the paint method or one of your methods called from the paint method.(needs the screen variable)

screen.drawImage(mypicture,30,30,100,100,this);

name of picture to draw

the x,y,width and height of the picture

The this keyword is used to keep track of whether the image is ready to load yet or not. Basically, you just have to remember that if you want the program to see if the Image has been loaded, use the this parameter. If you are not too concerned, use null as a parameter.

built in java method that finds your folder where the information is

name of the picture to store

Page 111: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 11-IMPORTING IMAGES AND SOUNDS 96

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 11.2 SHOWING A PICTURE ON AN APPLET Applet draws a picture on the display **You need to have a picture called happy.gif in

your folder to do this program**

import java.awt.*; public class ex112 extends java.applet.Applet{ Image mypicture; public void init() { mypicture=getImage(getCodeBase(),"happy.gif"); } public void paint(Graphics screen) { screen.drawImage(mypicture,30,30,100,100,this); } }//ends ex112

Section 11.2 Mastery Questions

1. Create an applet that displays a picture of your choice.

11.3 HOW SOUNDS ARE USED IN JAVA

**Unit 11.3 and 11.4 are Optional units, if your computer doesn’t have speakers,

skip these sections** Basically, sounds come in many different formats as do pictures. The format that

most Java programs can use is the .au, or .wav format. Sound files can be very large, and many of them maybe too large for your Java

program to handle. If your program compiles correctly but isn’t working, try using a smaller sound file and see if that helps.

11.4 BASIC STEPS IN USING SOUNDS IN YOUR PROGRAM

Table 11.4 Using sounds in your program Step Example

add the following import line import java.applet.*;

Make sure your sound file is stored in the same folder as your java program

Create the AudioClip variable to hold your sound.

AudioClip mysound;

Initialize the AudioClip variable in your init method so the sound is ready to be used.

mysound=getAudioClip(getCodeBase(),"temp.au");

Use play() method to make the sound appear at any time in any method

mysound.play();

Use the stop() method to make the sound stop.

mysound.stop();

Use the loop() method to make the sound loop over and over

mysound.loop();

built in java method that finds your folder where the information is

name of the sound to store

this is the name of the picture. Whatever picture you are using, put its name here. The picture should be in the same folder as your java program code

Page 112: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 11-IMPORTING IMAGES AND SOUNDS 97

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 11.4 USING THE LOOP() METHOD TO PLAY A SOUND Applet plays a sound over and over again. **You need to have a sound called yahoo1.au

in your folder to run this program**

import java.awt.*; import java.applet.*; public class ex114 extends java.applet.Applet{ AudioClip mysound; public void init() { mysound=getAudioClip(getCodeBase(),"yahoo1.au"); makesound(); } public void makesound() { mysound.loop(); } }//ends ex114

Section 11.4 Mastery Questions

1. Adjust the example 11.4 program so it only makes a sound once.

UNIT EXERCISES

(View exercise #1 and #2 in the appletviewer) 1. Create a large while loop, and animate the image of a ball so it bounces back and forth across the top of the applet display. **#2 is an optional question, if your computers don’t have speakers you cannot do it** 2.Add sound to the program made in #1, so that every-time the square bounces it makes a sound. 3.Create an applet that has 3 buttons which play different sounds depending on what button is pushed. (In the JDK there are some sounds in the demo folders, or find some sounds on the Internet, make sure they are in .au format)

make sure you have an .au sound in the same folder as the java program. Whatever the name of the sound is, put it here.

Page 113: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 11-IMPORTING IMAGES AND SOUNDS 98

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Page 114: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 12-MOUSE EVENTS 99

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 12 MOUSE EVENTS

UNIT OVERVIEW

• 12.1 What is a mouse event?

• 12.2 Basic Steps in handling mouse events in an applet

• 12.3 Drag and Drop Example

• 12.4 A simple doodle pad program example

12.1 WHAT IS A MOUSE EVENT?

A mouse event is anytime something is done with the mouse while the applet is running. It could be a mouse click, a mouse drag, letting go of the mouse, or simply moving the mouse around. In this unit, the basic mouse events will be shown and handled, along with a drag and drop example which is very useful when creating games.

12.2 BASIC STEPS IN HANDLING MOUSE EVENTS IN AN APPLET

Table 12.2 Using Mouse Events in your Program Steps Example

add event import line import java.awt.event.*;

add the MouseListener and MouseMotionListener interface to your program heading line

public class example extends java.applet.Applet implements MouseListener,MouseMotionListener {

add the event handlers to your applet in the init method

addMouseListener(this); addMouseMotionListener(this);

Add the following 7 methods to your applet. If you don’t want to execute any instructions when a specific mouse event occurs, just leave the instruction section blank. Put the instructions you want to execute when a certain mouse event occurs inside the specific event method. For example, If you want to do something when the person drags the mouse, put those instructions in the mouseDragged method etc…

public void mouseClicked(MouseEvent event) { output.append(“Mouse Clicked”+”\n”); } public void mousePressed(MouseEvent event) { instructions in here; } public void mouseReleased(MouseEvent event) { } public void mouseEntered(MouseEvent event) { } public void mouseExited(MouseEvent event) { } public void mouseDragged(MouseEvent event) { } public void mouseMoved(MouseEvent event) { }

this refers to the current applet

Page 115: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 12-MOUSE EVENTS 100

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 12.2 BASIC MOUSE HANDLING APPLET Applet display a running commentary on mouse events in a textarea

import java.awt.*; import java.awt.event.*; public class ex122 extends java.applet.Applet implements MouseListener,MouseMotionListener { TextArea output; public void init() { output=new TextArea(10,40); add(output); addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent event) { output.append("Mouse Clicked" + "\n"); } public void mousePressed(MouseEvent event) { output.append("Mouse Pressed" + "\n"); } public void mouseReleased(MouseEvent event) { output.append("Mouse Released" + "\n"); } public void mouseEntered(MouseEvent event) { output.append("Mouse Entered Applet" + "\n"); } public void mouseExited(MouseEvent event) { output.append("Mouse Exited" + "\n"); } public void mouseDragged(MouseEvent event) { output.append("Mouse Dragged" + "\n"); } public void mouseMoved(MouseEvent event) { output.append("Mouse Moved" + "\n"); } }//ends ex122

Section 12.2 Mastery Questions

1.Create your own program that demonstrates at least 4 of the mouse events mentioned.

12.3 DRAG AND DROP EXAMPLE

In many games and graphical programs the user is able to drag and drop objects on the playing surface. With this in mind, simple yet effective drag and drop sequence will be presented.**ALL OF THE DRAG DROP EXAMPLES (12.3a,12.3b,12.3c, ONLY DRAG HORIZONTALLY**

adding the event listener to the applet.

preparing applet to handle mouse events

The 7 required methods. These must be included. It is okay to leave the method blank but it still must be included

Page 116: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 12-MOUSE EVENTS 101

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Table 12.3a Steps involved in drag and drop Steps Example

Do all the mouse handling steps described in the above section add in the steps described below

Declare a variable of type rectangle (this is used to describe the box you will be moving. If your item is a picture, see example 12.3c)

Rectangle mybox;

initialize the rectangle in init() method

mybox=new Rectangle();

give the rectangle some starting coordinates in the init method

mybox.x=50; mybox.y=50; mybox.width=90; mybox.height=90;

in the paint method the first lines should refresh the background

screen.setColor(Color.white); screen.fillRect(0,0,1000,400);

the next lines in the paint method draw the object.

screen.setColor(Color.red); screen.fillRect(mybox.x,mybox.y,mybox.height,mybox.width);

in the mousePressed method, check to see if the person has clicked inside your rectangle. If they have, then prepare to drag the object by setting the variable called dragging to true. event.getX() and event.getY() just get the coordinates of where the mouse press occurred. The contains method checks to see if the click occurred in mybox.

public void mousePressed(MouseEvent event) { if (mybox.contains(event.getX(),event.getY())){ dragging=true; } }

In the mouseDragged method, we check to see if dragging is true, if it is, then we set the value of the x coordinate of mybox to the current x coordinate of the mouse (event.getX();) After this is done, we call the repaint method which will show the object in its new position.

public void mouseDragged(MouseEvent event) { if(dragging==true) { mybox.x=event.getX(); } repaint(); }

Add the update method to prevent screen from being cleared. We are redrawing the background ourselves in the paint method.

public void update(Graphics screen) { paint(screen); }

Add the rest of the mouse methods, leave them empty

event.getX(), and event.getY() get the mouses current x,y coordinates as integers

check to see if click occurred in mybox

Page 117: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 12-MOUSE EVENTS 102

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 12.3A SIMPLE DRAG AND DROP (HORIZONTAL) Applet lets the user drag a square horizontally across the screen

import java.awt.*; import java.awt.event.*; public class ex123a extends java.applet.Applet implements MouseListener,MouseMotionListener { Graphics screen; Rectangle mybox; boolean dragging; public void init() { mybox=new Rectangle(); mybox.x=50; mybox.y=50; mybox.width=50; mybox.height=50; addMouseListener(this); addMouseMotionListener(this); } public void paint(Graphics screen) { screen.setColor(Color.white); screen.fillRect(0,0,1000,400); screen.setColor(Color.red); screen.fillRect(mybox.x,mybox.y,mybox.height,mybox.width); } public void mouseDragged(MouseEvent event) { if(dragging==true) { mybox.x=event.getX(); } repaint(); } public void mousePressed(MouseEvent event) { if (mybox.contains(event.getX(),event.getY())){ dragging=true; } } public void update(Graphics screen) { paint(screen); } public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} public void mouseClicked(MouseEvent event) {} public void mouseMoved(MouseEvent event) {} }//ends ex123a

Page 118: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 12-MOUSE EVENTS 103

________________________________________________________________________ Copyright © 2000 Robbie Kailley

**ADVANCED DRAG AND DROP SECTION, OPTIONAL** The code in example 12.3b has been sectioned off into different methods, but that is not what causes an improvement in drag/drop. Compare the 12.3a code to 12.3b code. EXAMPLE 12.3B ADVANCED DRAG AND DROP (HORIZONTAL) Applet lets user drag square across the screen, more advanced use of drag and drop

import java.awt.*; import java.awt.event.*; public class ex123b extends java.applet.Applet implements MouseListener,MouseMotionListener { Graphics screen; Rectangle mybox; boolean dragging; int dx,originalx; public void init() { mybox=new Rectangle(); mybox.x=50; mybox.y=50; mybox.width=50; mybox.height=50; addMouseListener(this); addMouseMotionListener(this); } public void paint(Graphics screen) { screen.setColor(Color.white); screen.fillRect(0,0,1000,400); screen.setColor(Color.red); screen.fillRect(mybox.x,mybox.y,mybox.width,mybox.height); } public void mouseDragged(MouseEvent event) { dragbox(event); repaint(); } public void mousePressed(MouseEvent event) { if (mybox.contains(event.getX(),event.getY())){ startdrag(event); } } public void startdrag(MouseEvent event) { originalx=mybox.x; dx=event.getX()-originalx; dragging=true; } public void dragbox(MouseEvent event) { if(dragging==true) { mybox.x=event.getX()-dx; } }//ends drag box Program continued on next page �

Page 119: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 12-MOUSE EVENTS 104

________________________________________________________________________ Copyright © 2000 Robbie Kailley

public void update(Graphics screen) { paint(screen); } public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} public void mouseClicked(MouseEvent event) {} public void mouseMoved(MouseEvent event) {} }//ends ex123b

MOVING AN IMAGE (NOT OPTIONAL, EVERYONE SHOULD DO THIS SECTION) Moving an image is a matter of changing the images coordinates. Table 12.3b Steps in drag/drop with an image Steps Example

Use all the code mentioned above (example 12.3a or 12.3 b)with a few changes outlined below

Declare and make an image available into your program (see unit 11, section11.2). Make sure your image is a Gif or Jpeg, and that it is in the same folder as your program code

In your paint method, do not draw or fill the rectangle you have declared, its only use is for determining the drag drop for the image. Therefore, we do not need to see the rectangle.

ELIMINATE THE LINES: screen.setColor(Color.red); screen.fillRect(mybox.x,mybox.y,mybox.width,mybox.height);

In your paint method, include the line which draws the image to the current rectangle coordinates (which are being adjusted by the drag/drop program code)

screen.drawImage(mypicture,mybox.x,mybox.y,mybox.width,mybox.height);

Page 120: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 12-MOUSE EVENTS 105

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 12.3C DRAG AND DROP WITH IMAGES (HORIZONTAL) Applet lets the user drag an image across the screen

import java.awt.*; import java.awt.event.*; public class ex123c extends java.applet.Applet implements MouseListener,MouseMotionListener { Graphics screen; Rectangle mybox; boolean dragging; Image face; public void init() { face=getImage(getCodeBase(),"happy.gif"); mybox=new Rectangle(); mybox.x=50; mybox.y=50; mybox.width=50; mybox.height=50; addMouseListener(this); addMouseMotionListener(this); } public void paint(Graphics screen) { screen.setColor(Color.white); screen.fillRect(0,0,1000,400); screen.drawImage(face,mybox.x,mybox.y,mybox.height,mybox.width,this); } public void mouseDragged(MouseEvent event) { if(dragging==true) { mybox.x=event.getX(); } repaint(); } public void mousePressed(MouseEvent event) { if (mybox.contains(event.getX(),event.getY())){ dragging=true; } } public void update(Graphics screen) { paint(screen); } public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} public void mouseClicked(MouseEvent event) {} public void mouseMoved(MouseEvent event) {} }//ends ex123c

Page 121: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 12-MOUSE EVENTS 106

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 12.3 Mastery Questions

1.Change the drag and drop code for example 12.3a (or 12.3b if you did the optional advanced example). Make the drag and drop work vertically (up and down) as well as side to side. This way, the user should be able to drag the box anywhere on the screen. 2.Change example 12.3c so the drag and drop works in all directions as well.

12.4 A SIMPLE DOODLE PAD PROGRAM EXAMPLE

You can use mouse events to create programs that draw objects in specific locations on the screen. For example, you can create a program that draws a rectangle on the screen wherever the mouse is clicked. You could also create a program that lets you resize shapes by clicking and dragging on the object on the screen. To do these types of programs just requires manipulation of the event.getX() and event.getY() methods. EXAMPLE 12.4 A SIMPLE DOODLE PAD EXAMPLE USING MOUSE EVENTS User can draw in the applet by clicking and dragging the mouse around.

import java.awt.*; import java.awt.event.*; public class ex124 extends java.applet.Applet implements MouseListener,MouseMotionListener { int x,y,oldx,oldy; Graphics screen; boolean dragging; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void paint(Graphics screen) { screen.setColor(Color.red); screen.drawLine(oldx,oldy,x,y); oldx=x; oldy=y; } public void mouseDragged(MouseEvent event) { if(dragging==true) { x=event.getX(); y=event.getY(); } repaint(); } public void mousePressed(MouseEvent event) { oldx=event.getX(); oldy=event.getY(); dragging=true; } public void update(Graphics screen) { paint(screen); } public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {}

draws a line from the previous position of the mouse to the new current position of the mouse as

its being dragged

set the previous position of the mouse to the new current position of the mouse. So as the mouse is dragged, the line continually updated from where the mouse was to where the mouse currently is.

gets the current x,y position of the mouse and then call up the paint method.

sets the starting position of the doodling to the position where the mouse is first pressed

Program continued on next page �

Page 122: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 12-MOUSE EVENTS 107

________________________________________________________________________ Copyright © 2000 Robbie Kailley

public void mouseExited(MouseEvent event) {} public void mouseClicked(MouseEvent event) {} public void mouseMoved(MouseEvent event) {} }//ends ex124

Section 12.4 Mastery Questions

1. Adjust the example 12.4 , so there is a drop down menu that lets you choose the current color. (Hint: You will also need to implement an ItemListener to make the menu bar work)

UNIT EXERCISES

1.Create an applet that draws a rectangle in the middle of the screen. Make it so the user can click inside the rectangle and change its size by dragging the mouse (like paint programs when you change the size of rectangles). 2.Create an applet that draws an oval where-ever the user clicks on the applet display. Then if the user clicks inside of the oval and begins dragging, the oval should follow. When the user stops dragging, the oval stays in the spot where the mouse dragging stopped.

Page 123: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 12-MOUSE EVENTS 108

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Page 124: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 13-KEYBOARD EVENTS 109

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 13 KEYBOARD EVENTS

UNIT OVERVIEW

• 13.1 What is a keyboard event?

• 13.2 Basic steps in declaring and using keyboard events

• 13.3 Common key codes

13.1 WHAT IS A KEYBOARD EVENT?

A keyboard event occurs whenever the user enters something in using the keyboard. Quite commonly, programs will make something move or do some specific action depending on what key is pressed. In this unit, the vary basics of key events will be shown, which should enable you to incorporate them into your applets.

13.2 BASIC STEPS IN DECLARING AND USING KEYBOARD EVENTS

Table 13.2 Using keyboard events in an applet Steps Examples

add import events line to program import java.awt.event.*;

add the KeyListener interface to your program heading line

program ex132 extends java.applet.Applet implements KeyListener {

add requestFocus(); command to init method. This commond prepares the applet to accept keyboard events.

requestFocus();

add the event listener to your applet in the init method

addKeyListener(this);

Add the following 3 methods to your applet. If you don’t want to execute any instructions when a specific key event occurs, just leave the instruction section blank. If you want to do something when the person presses,types or releases a certain key, put those instructions in the proper method.

public void keyPressed(KeyEvent event) {} public void keyReleased(KeyEvent event) {} public void keyTyped(KeyEvent event) {}

The method we will be using the most is keyPressed. To check to see what key has been pressed, we refer to the unicode character of the key (which is an integer that identifies what key has been pressed.). To get the integer code for a key, we use the command event.getKeyCode(); and store the result in an integer variable. In the example, the integer variable is called character_int.

public void keyPressed(KeyEvent event) { character_int=event.getKeyCode(); output.append("The code for the key pressed is" + character_int+"\n"); if (character_int==32) { output.append("You pressed the space bar"+"\n"); } }//ends keyPressed

this refers to the current applet

the event.getKeyCode() gets the integer value of the key. We store it in an int variable

Page 125: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 13-KEYBOARD EVENTS 110

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 13.2A BASIC KEY EVENT EXAMPLE. PRINTS OUT KEY CODES Applet that prints out messages in Text Area as keys are pressed and released.

import java.awt.*; import java.awt.event.*; public class ex132a extends java.applet.Applet implements KeyListener { TextArea output; int character_int; public void init() { requestFocus(); output=new TextArea(10,40); add(output); addKeyListener(this); } public void keyPressed(KeyEvent event) { character_int=event.getKeyCode(); output.append("The code for the key pressed is" +character_int+"\n"); if (character_int==32) { output.append("You pressed the space bar"+"\n"); } } public void keyReleased(KeyEvent event) { output.append("A key has been released"+"\n"); } public void keyTyped(KeyEvent event) { output.append("A key has been typed"+"\n"); } }//end ex132a

we use an if then to compare the keycode for the key the user just pressed, to the number known to represent a spacebar. If they are the same, print the message

Page 126: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 13-KEYBOARD EVENTS 111

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 13.2B USING KEY EVENTS IN A GRAPHICAL APPLET This applet moves a box horizontally when the right or left arrow keys are pressed.

import java.awt.*; import java.awt.event.*; public class ex132b extends java.applet.Applet implements KeyListener { Graphics screen; int character_int; Rectangle mybox; public void init() { requestFocus(); mybox=new Rectangle(); mybox.x=200; mybox.y=200; mybox.width=20; mybox.height=20; addKeyListener(this); } public void paint(Graphics screen) { screen.setColor(Color.white); screen.fillRect(0,0,400,400);//this refreshes the background screen.setColor(Color.blue); screen.fillRect(mybox.x,mybox.y,mybox.width,mybox.height); } public void update(Graphics screen) { paint(screen); } public void keyPressed(KeyEvent event) { character_int=event.getKeyCode(); if (character_int==37) { mybox.x=mybox.x-1; } if (character_int==39) { mybox.x=mybox.x+1; } repaint(); //calls up paint method again } public void keyReleased(KeyEvent event) { } public void keyTyped(KeyEvent event) { } }//end ex132b

we add in our version of update so when repaint is called, the screen will not be cleared. We are refreshing the background ourselves in the first 2 lines of the paint method

we use an if then to compare the keycode for the key the user just pressed to a series of known codes that represent directional arrows on the keyboard.

we adjust the position if the left arrow key is pressed, move box to left by 1 pixel if the right arrow

key is pressed,move box to right by 1

Get the integer code for the key that was pressed

Page 127: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 13-KEYBOARD EVENTS 112

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 13.2C USING KEY EVENTS TO MOVE AN IMAGE This applet moves an image horizontally when the right or left arrow keys are pressed

import java.awt.*; import java.awt.event.*; public class ex132c extends java.applet.Applet implements KeyListener { Image pic; Graphics screen; int character_int; Rectangle mybox; public void init() { requestFocus(); pic=getImage(getCodeBase(),"happy.gif"); mybox=new Rectangle(); mybox.x=200; mybox.y=200; mybox.width=50; mybox.height=50; addKeyListener(this); } public void paint(Graphics screen) { screen.setColor(Color.white); screen.fillRect(0,0,400,400);//this refreshes the background screen.drawImage(pic,mybox.x,mybox.y,mybox.width,mybox.height,this); } //we add in our version of update public void update(Graphics screen) { paint(screen); } public void keyPressed(KeyEvent event) { character_int=event.getKeyCode(); //if the left arrow key is pressed, move box to left by 1 pixel if (character_int==37) { mybox.x=mybox.x-1; } //if the right arrow key is pressed,move box to right by 1 pixel if (character_int==39) { mybox.x=mybox.x+1; } repaint(); //calls up paint method again } public void keyReleased(KeyEvent event) { } public void keyTyped(KeyEvent event) { } }//end ex132c

we use the rectangle mybox coordinates to define where the image will be drawn.We do not need to actually draw the rectangle.

Page 128: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 13-KEYBOARD EVENTS 113

________________________________________________________________________ Copyright © 2000 Robbie Kailley

13.3 COMMON KEY CODES

You can use example 13.2a to determine the integer key codes for any key on the

keyboard. It will print out the key code in a textarea. For handy reference, a table of common key codes is provided. Table 13.3 Common Key Codes Keys Key Code (integer)

space bar 32

up arrow 38

down arrow 40

left arrow 37

right arrow 39

CTRL key 17

Alt key 18

Shift key 16

Enter key 10

UNIT EXERCISES

1. Adjust applet example 13.2b and 13.2c so the box or Image can be moved vertically as well as horizontally. 2.Create a program that uses key events (use your imagination!).

Page 129: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 13-KEYBOARD EVENTS 114

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Page 130: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 14-OBJECT ORIENTED PROGRAMMING 115

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 14:OBJECT ORIENTED PROGRAMMING

UNIT OVERVIEW

• 14.1 What is Object Oriented Programming (OOP)?

• 14.2 Advantages of OOP

• 14.3 Basic overview of how to create oop programs

• 14.4 What is a modifier?

• 14.5 Basic class construction

• 14.6 Adding methods to your class

• 14.7 Creating the main applet program which uses the car.java class

• 14.8 Final word on basic OOP

• 14.9 Creating a class file within the main Applet code (Optional)

14.1 WHAT IS OBJECT ORIENTED PROGRAMMING (OOP)?

In object oriented programming (called OOP), there are some new words you will have to learn. The basic definitions are provided in the table below for easy reference. A detailed explanation follows the table. Table 14.1 OOP Definitions OOP Word Meaning

class name of the blueprint for an object

properties variables of a class

behaviours methods of a class

DETAILED EXPLANATIONS OF CLASSES AND OBJECTS PROPERTIES AND BEHAVIOURS

When we look at the world around us, we can see that objects surround us. Each object has its own set of properties and behaviors. A class is a blueprint for an object. It contains all the variables and methods that define something. Then from that blueprint we can create as many objects as we desire.

For example, we could define a class called car. All cars have certain properties, which make them cars. They have steering wheels, 4 tires and headlights (hopefully!). These properties are the variables of the car class.

A car also is able to move. It's able to honk and it's able to turn off and on its headlights. These are the behaviors of the car. The behaviors are the methods of the class.

Summary of car class: Variables (properties) : steering wheels, 4 tires, headlights Methods (behaviours) : move, honk, turn headlights on and off

Page 131: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 14-OBJECT ORIENTED PROGRAMMING 116

________________________________________________________________________ Copyright © 2000 Robbie Kailley

In our example, now that we have defined the car class, we can create many objects of that class. For example, BMW, Nova, Honda are all objects of the class car. They all follow the blueprint of the car, but they have different values for the variables. Honda and BMW's both have steering wheels but they are probably different styles and colors. All the cars have 4 wheels but they may be of a different brand. All of these specific types of car move differently than eachother. So, from the car class, we can create many different car objects.

14.2 ADVANTAGES OF OOP.

You will see the following advantages as you begin programming the examples, and even adjusting your programs to use OOP concepts.

• Each object knows how to behave itself and take care of itself.

• The program becomes easier to debug, and change.

• It becomes easier to add more objects to the program.

• More portable programs

• More reusability

14.3 BASIC OVERVIEW OF HOW TO CREATE OOP PROGRAMS

The basic steps to follow when creating a program using OOP are shown in the diagram below.

This your class file. It is java code that contains all the properties and behaviours of your class. On its own, this file will not do anything. It serves only as a blueprint to be used in another program. For example we can make a car class: Properties 4 wheels steering wheel. Behaviours drive honk the horn

This is your java program code. In here, you will create objects from the class file. For example. in this program we could make a honda and BMW car. The program would know what a car is because the separate class file defines it for us. We could then give each car different types of wheels and a different steering wheel. We could also tell the cars to drive and honk the horn. The cars will know how to do these things because they are defined in the class file

Step 1: Create and compile the class code Make sure the class code and the main applet code (in Step 2) are in the same folder,so the main applet code can access the class code

Step 2: Create and compile your applet code. In your applet code, you can now make objects from the blueprint defined in the class code. You can call up all the methods and initialize all the blueprint(class) variables for your objects

Page 132: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 14-OBJECT ORIENTED PROGRAMMING 117

________________________________________________________________________ Copyright © 2000 Robbie Kailley

14.4 WHAT IS A MODIFIER?

A modifier is a word used to describe the accessibility of a variable, method or a class. The useful of modifiers in class construction will be discussed in the next unit. For now, just familiarize yourself with the names. Table 14.4 Modifiers Modifier Classes Methods Variables

public accessible everywhere

accessible everywhere

accessible everywhere

private n/a not inherited by subclasses

not accessible by other classes

final cannot subclass this class

method cannot be overridden

constant value for the variable once its value is initially set

Page 133: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 14-OBJECT ORIENTED PROGRAMMING 118

________________________________________________________________________ Copyright © 2000 Robbie Kailley

14.5 BASIC CLASS CONSTRUCTION

We will first create a class that defines a car. Each car object will need 3 things to set itself up for use.1)A name 2)The x location for the left side of the car 3)The y location for the top location of the car. SAVE THIS EXAMPLE AS car.java

import java.awt.*; public class car { String carname; int x,y; Color mycolor; int carspeed;

public car(String name,int left,int top) { carname=name; x=left; y=top;

} }//ends car class

Section 14.5 Mastery Questions

1.Type in the code for car.java, save it and compile it. When you try to run it doesn anything happen? 2.What is the purpose of the constructor?

The class defines what a car is. It is the blueprint for all cars. You don't need to have the class in the same file as your applet program. It just needs to be in the same folder

modifer can be either public or final. final will be discussed in next section

save the java file with the same name as your class file.

The name would be car.java

These are the class variables. They can be accessed by any method in this class. If there is no modifier before a variable name, it defaults to a public variable. This means it is accessible anywhere in the program

This is a special method called the constructor. It has the same name as the class, and has no void in the heading. The constructor is the first method called when an object is created from this class, so its job is to get the variables needed initially to set up the object. These are variables which will be received when the constructor is called. An example call to this method would look like mycar=new car(“My Car”,10,10);

**You have been using constructors from the beginning of this book. Remember output=new TextArea(10,50);

we are giving the class variables the values of the incoming variables from the constructor. This way we can use the variables in any other method in this class. This is always done. This is called localizing the variables.

Page 134: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 14-OBJECT ORIENTED PROGRAMMING 119

________________________________________________________________________ Copyright © 2000 Robbie Kailley

3.Make up a written example of a class definition and various types of objects you could create from that definition (do not program this, it’s a written exercise)

14.6 ADDING METHODS TO YOUR CLASS

Now that you have created the very basics of the car class, we need to add some methods to create some behaviours for our cars. Add each of the methods described below to car.java

Compile your code after typing in each method. We need to look at basic method construction for a moment, so if you haven’t completed the method interlude section, please do that now, before going any further in this unit. METHOD 1 GETCOLOR() A car should know its color. Therefore, it should be possible to set the color of the car in the class.

public void getcolor(Color clr) { mycolor=clr; }

METHOD 2 GETSPEED()

public int getspeed() { //this variable is a local variable to this method only. int speed; speed=(int)(100*Math.random()); //here we return the value of speed whenever this method is called return speed; }

METHOD 3 DRAWCAR()

public void drawcar(Graphics screen) { carspeed=getspeed(); //get a random number to represent speed of car screen.setColor(mycolor); screen.drawRect(x,y,50,20); screen.drawOval(x+10,y+20,10,10); screen.drawOval(x+40,y+20,10,10); screen.drawString(carname,x+4,y+60); screen.drawString("Speed = "+carspeed,x+4,y+75); }

We will be calling this method in the main applet code so its modifier is public.

We take in the color clr and we localize it to mycolor so we can use that variable in the other class methods. Again , if we didn’t do this, we would only be able to use clr in this method which is pretty useless since all the drawing will be done in a different method.

this method doesn’t take in anything but it returns an integer number representing speed when its called

this method will draw the car. It needs to have the (Graphics screen) sent to it so it can draw on the applet. It uses the values that were localized in the constructor.(x,y,carname) and localized/created in methods (carspeed,mycolor) . They are all class variables, which means they were declared in the main variable section so they can be used here)

Page 135: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 14-OBJECT ORIENTED PROGRAMMING 120

________________________________________________________________________ Copyright © 2000 Robbie Kailley

NOTE: car.java doesn't do anything on its own. You have just created the blueprint. Now in your main applet code (the class that extends java.applet.Applet) you must create objects from this class. You have 2 choices as to where to put this c1ass called car.java (I use the first method)

• You can save this as a separate file called car.java and save it in the same folder as your main applet code. The compiler should automatically compile this class when you compile you main applet, but if it doesn't then you have to compile this separately.

• You can put the code in the same file as your main applet code. Just add the class code at the end of your regular applet code. (outside of the last brace that ends the main applet class). When you compile the main applet code it will automatically compile this class. (shown in section 14.9)

COMPLETE CAR.JAVA CODE EXAMPLE CAR.JAVA THE COMPLETE CODE FOR CAR.JAVA This is the class code for car. It doesn’t do anything on its own, it’s just a blueprint.

import java.awt.*; public class car { String carname; int x,y,carspeed; Color mycolor; public car(String name,int left,int top) { carname=name; x=left; y=top; } public void getcolor(Color clr) { mycolor=clr; } public int getspeed() { //this variable is a local variable to this method only. int speed; speed=(int)(100*Math.random()); //here we return the value of speed whenever this method is called return speed; } public void drawcar(Graphics screen) { carspeed=getspeed(); //get a random number to represent speed of car screen.setColor(mycolor); screen.drawRect(x,y,50,20); screen.drawOval(x+10,y+20,10,10); screen.drawOval(x+40,y+20,10,10); screen.drawString(carname,x+4,y+60); screen.drawString("Speed = "+carspeed,x+4,y+75); } }//ends car.java

Page 136: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 14-OBJECT ORIENTED PROGRAMMING 121

________________________________________________________________________ Copyright © 2000 Robbie Kailley

14.7 CREATING THE MAIN APPLET PROGRAM WHICH USES THE CAR.JAVA

CLASS

In the last section we created the blueprint for a car. We haven’t actually created any cars yet. It is like we have the plan for a car on a piece of paper, now we have to go to the factory and actually create a car for real. To create a car from the blueprint is called creating an object from a class. The blueprint is the class. The car is the object created from the class (called an instance of the class). Creating the main applet code will be done in a series of steps.

NOTE :Make sure your class code and the main applet code are always in the same folder

STEP 1. THE BASIC APPLET FRAMEWORK Save the following code as ex147.java MAKE SURE ITS IN THE SAME FOLDER AS CAR.JAVA

import java.awt.*; public class ex147 extends java.applet.Applet { }//ends main applet program

STEP 2. INITIALIZING YOUR CAR OBJECTS To do this you must adjust the step 1 code to the following.

import java.awt.*; public class ex147 extends java.applet.Applet { car my_car,dads_car;

public void init() { my_car=new car("My Car",10,10); dads_car=new car("Dads car",300,10); } }//ends main applet program

car is the class, and dads_car is a specific instance of this class.

You are declaring 2 variables of type car. Your program knows what a car is because you have defined a car in the code for car.java.

initializing the objects for use by calling calling the constructor method for the car class you made. Similar to creating next TextFields buttons etc..

the constructor is expecting a string and 2 numbers. You must send them in the proper order. (Refer to car.java if you forgot the order)

Page 137: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 14-OBJECT ORIENTED PROGRAMMING 122

________________________________________________________________________ Copyright © 2000 Robbie Kailley

At this point you have declared and initialized two objects for use. HOW TO CALL METHODS OF AN OBJECT (BEHAVIOURS) After initializing the objects, we need to let the objects do something. This means we need to call up behaviours (methods) of the object. Since our cars are going to be drawing themselves, we need to let the main program somehow access or call up the drawing method for each car. Also, each car needs a color, so we need to call up the method that gets the color for each car. Since both of these methods involve drawing, we will call them up in the main applets paint method. The main applets Graphics variable screen will be sent to the object’s methods so the object can draw to the main applet window. Adjust the code for example 147 to the following.

import java.awt.*; public class ex147 extends java.applet.Applet { car my_car,dads_car; public void init() { my_car=new car("My Car",10,10); dads_car=new car("Dads car",300,10); } public void paint (Graphics screen) { my_car.getcolor(Color.red); dads_car.getcolor(Color.blue); my_car.drawcar(screen); dads_car.drawcar(screen); } }//ends main applet program

each car you declare has the methods created in car.java available to it. To call up a method, you simply put the name of the object followed by the name of the method with the proper parameters sent to it. getcolor method needs a color sent to it, so we send it Color.red for my_car, and for dads_car we send it Color.blue. If we had another car called mom_car, we could call up mom_car.getcolor(Color.yellow);

each car can call up the drawcar method. The drawcar method needs the screen variable because the car will be drawing to the applet screen. If we had another car called mom_car, we could call: mom_car.drawcar(screen);

Page 138: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 14-OBJECT ORIENTED PROGRAMMING 123

________________________________________________________________________ Copyright © 2000 Robbie Kailley

THE COMPLETE VERSION OF EX147.JAVA

EXAMPLE 14.7 THE COMPLETE VERSION COMBINING ALL THE ABOVE STEPS This is the main applet code which creates and uses objects from the car.java class we

created.

import java.awt.*; public class ex147 extends java.applet.Applet { car my_car,dads_car; //2 objects of type car public void init() { my_car=new car("My Car",10,10); dads_car=new car("Dads car",300,10); } public void paint (Graphics screen) { my_car.getcolor(Color.red); dads_car.getcolor(Color.blue); my_car.drawcar(screen); dads_car.drawcar(screen); } }//ends main applet program

RUNNING A PROGRAM WHEN YOU HAVE 2 (OR MORE) SEPARATE FILES

• compile each of your class files first (i.e. compile car.java first)

• compile your main applet code last (i.e. compile ex147 last)

• create a web page applet that calls up the class of the main applet code. i.e.

<html> <applet code=”ex147.class” height=400 width=400></applet> </html>

• run your web page as usual using the applet viewer or a web browser. Section 14.7 Mastery Questions

1. Add another method to car.java which takes in the name of the person driving the car. In the drawcar method, the name should be printed below the speed 2.Create 2 more car objects called mom_car and grandpa_car. Initialize and use these objects also. Display them on the screen along with the other cars (but below them).

Here you are creating 2 new objects of type car. You are calling the constructor and sending it the proper data it needs to set up the object.

Here you are calling the methods of each object. The methods that are available to the objects are the methods that are defined in the car class

Page 139: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 14-OBJECT ORIENTED PROGRAMMING 124

________________________________________________________________________ Copyright © 2000 Robbie Kailley

14.8 FINAL WORD ON BASIC OOP

As you can see from mastery question #2 above, the advantage of using OOP is quite huge. Once you have created a class file, you can create as many objects as you want from that class, and it doesn’t take much more work!!. There are many other things to learn about OOP, we will examine more advanced topics in the next unit. OOP is a core aspect of programming which you will see more of if you go on to higher level programming courses. After learning the basics, you should be well on your way to understanding the more advanced concepts.

14.9 CREATING A CLASS FILE WITHIN THE MAIN APPLET CODE (OPTIONAL)

It is possible to place a class file in the same code as the main applet code. This way you only have to compile 1 file, because the class file gets compiled automatically. (Actually, many compilers will find the class file even if its in a separate file, try yours and see if it works). The only problem is that the file gets large very quickly if your program has some degree of complexity to it. You can decide how you want to organize your code. Most often, class files are separate. . EXAMPLE 14.9 COMBINING CLASS AND MAIN APPLET CODE Program Code contains the class and main applet code in one file

import java.awt.*; public class ex149 extends java.applet.Applet { car my_car,dads_car; public void init() { my_car=new car("My Car",10,10); dads_car=new car("Dads car",300,10); } public void paint (Graphics screen) { my_car.getcolor(Color.red); dads_car.getcolor(Color.blue); my_car.drawcar(screen); dads_car.drawcar(screen); } }//ends main applet program //just add the class code after the main applet code is complete class car { String carname; int x,y; Color mycolor; int carspeed; public car(String name,int left,int top) { carname=name; x=left; y=top; } public void getcolor(Color clr) { mycolor=clr; }

take out the word public in front of the program heading line for the car.java code. Also, you can remove the import line that was in car.java originally because we already have it up top

Program continued on next page �

Page 140: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 14-OBJECT ORIENTED PROGRAMMING 125

________________________________________________________________________ Copyright © 2000 Robbie Kailley

public int getspeed() { //this variable is a local variable to this method only. int speed; speed=(int)(100*Math.random()); //here we return the value of speed whenever this method is called return speed; } public void drawcar(Graphics screen) { carspeed=getspeed(); //get a random number to represent speed of car screen.setColor(mycolor); screen.drawRect(x,y,50,20); screen.drawOval(x+10,y+20,10,10); screen.drawOval(x+40,y+20,10,10); screen.drawString(carname,x+4,y+60); screen.drawString("Speed = "+carspeed,x+4,y+75); } }//ends car.java class

WHEW! That's a lot of information in a short time. However, you have just gone through the fundamentals of OOP. There is more to come but now, we need some practice in making our own objects!

UNIT EXERCISES:

1)Create a class called human. It should have a constructor that takes in 2 arguments, the x and y location of the human. It should have a drawFace method that draws two eyes a nose and a smile. Create a method in the class called getname which gets a name for the human. Create an applet that has 3 objects of type human. They should be in different locations on the screen. Each objects should have it's own name. 2)Add another method to the human class which draws arms and a body on each person.

Page 141: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 14-OBJECT ORIENTED PROGRAMMING 126

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Page 142: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 15-OBJECT ORIENTED PROGRAMMING II 127

ADVANCED OBJECT CONSTRUCTION

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 15:OBJECT ORIENTED PROGRAMMING II:ADVANCED OBJECT CONSTRUCTION:

UNIT OVERVIEW:

• 15.1 Encapsulation

• 15.2 Polymorphism

• 15.3 Inheritance

• 15.4 Some notes and tips when using inheritance

• 15.5 Final thoughts about the introduction to OOP

15.1 ENCAPSULATION

Encapsulation is a way of programming so that class variables are only allowed to have their values set through methods and not by direct reference to an object’s variable. We want to strictly control the main applet program code’s access to the variables of an object. This will keep objects as independent as possible. The method called getcolor in the last unit used encapsulation.

Example of encapsulation in car.java (the class file) we created the following variable and method: Color mycolor; public void getcolor(Color clr) { mycolor=clr; } This method takes in a color (called clr)from the main program and then sets the class variable called mycolor to the variable called clr which is obtained from an external source. You always want to set the values of a class variable through methods of the

class. In the main program the call to getcolor look like this: my_car.getcolor(Color.red); The variable called mycolor is never accessed outside the class code, instead, we created a method called getcolor. This method takes in an external variable and then sets the value of the class variable mycolor to the value of the external variable.

Example of non-encapsulation (you want to avoid doing this) The alternative THAT YOU WANT TO AVOID would be to set the variable directly from the main applet code: my_car.my_color=Color.red; As you can see, there is no call to a method, you are setting the value of the objects’ variable directly from the main applet code. In a complex program when you are debugging this can make things difficult, as you do not know exactly where a variable may have been set or changed. AVOID DOING THIS

Page 143: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 15-OBJECT ORIENTED PROGRAMMING II 128

ADVANCED OBJECT CONSTRUCTION

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 15.1 Mastery Questions

1.In what way does the drawcar method from the previous unit (in car.java) use encapsulation?

15.2 POLYMORPHISM

When creating objects we want to keep them as flexible and dynamic as possible. For example, we may want to create a car object by sending it the x,y coordinates and the color we want to draw it. Also, we may want to create a car and only send it the x and y coordinates. We will need 2 constructors to do this. They will have the same name, but will accept a different number of parameters. This is known as polymorphism. Example 2 different constructors with the same name (polymorphism) Constructor number 1 public car(String name,int left,int top) {

carname=name; x=left; y=top; }

or Constructor number 2 public car(String name,int left,int top,Color clr) {

carname=name; x=left; y=top; mycolor=clr; }

How does the object know which constructor (or method ) to use? It is smart, it automatically knows depending on the number and type of parameters you use to call up the constructor or method. my_car=new car("My Car",10,10,Color.blue); my_car=new car("My Car",10,10); You can also create many different versions of any method in your program.

This will automatically use the second constructor, because it has the proper number and type of parameters

This will use the first

constructor.

Page 144: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 15-OBJECT ORIENTED PROGRAMMING II 129

ADVANCED OBJECT CONSTRUCTION

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Example: 2 different versions of getcolor method version #1 public void getcolor(Color carcolor) { mycolor=carcolor; mycolor2=Color.black; } version #2 public void getcolor(Color carcolor,Color wheelcolor) { mycolor=carcolor; mycolor2=wheelcolor; } When you call up the method through your objects, it automatically chooses the correct one: my_car.getcolor(Color.blue); //this calls the 1st version of the method or my_car.getcolor(Color.blue,Color.red); //this uses the 2nd version of the method

For this next example, save it as car.java. Then save the main applet code (next page) as ex152.java. Finally create the web page that will load up ex152 to view the applet. EXAMPLE CAR.JAVA THIS IS THE CLASS FILE WHICH USES POLYMORPHISM IN ITS

CONSTRUCTOR AND GETCOLOR METHOD The class file. Notice the use of 2 different constructors and 2 different getcolor methods.

import java.awt.*; public class car { String carname; int x,y; Color mycolor,mycolor2; public car(String name,int left,int top) { carname=name; x=left; y=top; } public car(String name,int left,int top,Color clr) { carname=name; x=left; y=top; mycolor=clr; } public void getcolor(Color carcolor) { mycolor=carcolor; mycolor2=Color.black; } public void getcolor(Color carcolor,Color wheelcolor) { mycolor=carcolor; mycolor2=wheelcolor; } public void drawcar(Graphics screen) {

2 different constructors

2 different getcolor() methods

Program continued on next page �

Page 145: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 15-OBJECT ORIENTED PROGRAMMING II 130

ADVANCED OBJECT CONSTRUCTION

________________________________________________________________________ Copyright © 2000 Robbie Kailley

screen.setColor(mycolor); screen.drawRect(x,y,50,20); screen.setColor(mycolor2); screen.drawOval(x+10,y+20,10,10); screen.drawOval(x+40,y+20,10,10); screen.drawString(carname,x+4,y+60); } }//ends car.java class

EXAMPLE 15.2 MAIN APPLET CODE WHICH USES THE CAR CLASS DEFINED ABOVE Applet draws 2 cars on the screen. Notice the calls to the different polymorphism

methods.

import java.awt.*; public class ex152 extends java.applet.Applet { car my_car,dads_car; //2 objects of type car public void init() { //here you are creating 2 new objects of type car. //you are calling the constructor and sending it the //proper data it needs to set up the object. my_car=new car("My Car",10,10); dads_car=new car("Dads car",300,10,Color.red); } public void paint (Graphics screen) { //here you are calling the methods of each object. //the methods that are available to the objects are the // the methods that are defined in the car class my_car.getcolor(Color.red); dads_car.getcolor(Color.blue,Color.green); my_car.drawcar(screen); dads_car.drawcar(screen); } }//ends main applet program

Section 15.2 Mastery Questions

1.Type in and compile car.java and ex152.java. Run the applet 2.Create 2 versions of a method that draws a door on the car. One version of the method doesn’t take in any parameters and draws the door with the same color as the wheels. The other version of the method will take in a color and draw only the door with that color. Create 2 cars on your applet display, each should use a different version of the door method you created.

15.3 INHERITANCE

Just like human beings can inherit traits from their parents, we can create a brand new class which will “inherit” methods and variables from a previously created class (called a parent class). The parent class is often called the “superclass”. The child class is often called the “subclass”.

each of these calls a different version of the getcolor method. You can tell because of the different numbers of parameters sent.

each of these calls a different version of the constructor method. You can tell because of the different numbers of parameters sent.

Page 146: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 15-OBJECT ORIENTED PROGRAMMING II 131

ADVANCED OBJECT CONSTRUCTION

________________________________________________________________________ Copyright © 2000 Robbie Kailley

The advantage in using inheritance is:

• This is used to help reduce the amount of code you type in. It helps make your code reusable. Many classes we create will use mostly the same methods as previously created classes except for a few change or a few additional methods. There is no point typing in the same code over and over again. We can create a subclass and add or change any of the methods inherited from the parent class.

INHERITANCE EXAMPLE EXPLANATION We will create a vehicle class that will have 2 subclasses. A car class and a truck class. CREATING THE VEHICLE PARENT CLASS (SUPERCLASS)

First we will create the vehicle class. It has all the basic foundation methods and variables which are common to its subclasses. Create a file called vehicle.java and add the following code to it: VEHICLE CODE. THIS IS CODE IS JUST A DEFINITION OF A VEHICLE. IT WILL BE

SUBCLASSED IN THE NEXT 2 PROGRAMS CALLED A_CAR AND A_TRUCK. Program doesn’t draw anything, its just a class file used for definition of a vehicle.

import java.awt.*; //this is the general description for what all vehicles have //notice in the main program called ex153.java I never actually create a vehicle object class vehicle { int left,top; String name; public vehicle(int x,int y,String z) { left=x; top=y; name=z; } public void paintbody(Graphics screen,Color clr) { screen.setColor(clr); screen.drawRect(left,top,80,50); screen.drawOval(left+20,top+50,10,10); screen.drawOval(left+45,top+50,10,10); screen.drawString(name,left+20,top+20); } }//end vehicle class

Vehicle

car truck

Page 147: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 15-OBJECT ORIENTED PROGRAMMING II 132

ADVANCED OBJECT CONSTRUCTION

________________________________________________________________________ Copyright © 2000 Robbie Kailley

GENERAL STRUCTURE WHEN CREATING A SUBCLASS To create a subclass, you name the class and then add the word extends and the name

of the parent class it is inheriting from.

Example public class a_car extends vehicle{ }

We will create 2 subclasses of vehicle, called a_car and a_truck. They inherit all the methods and variables of the vehicle class and adds some of their own. THE SUPER(PARAMETER) CALL EXPLAINED In the constructor of the subclass, you must make a call to constructor of the superclass, and send it the proper parameters so the basic foundation can be created. To make this call you put the following line at the beginning of the constructor method of your subclass : super(parameters);

The parameters are what is needed by the constructor of the superclass to create the foundation. (see the example code for a_car.java) CREATING THE CAR SUBCLASS

A_CAR CODE. THIS IS A SUBCLASS OF VEHICLE (NOTICE USE OF SUPER( ) METHOD) This is only a class file, it will not do anything on its own, it just defines what a_car is.

import java.awt.*; class a_car extends vehicle{ int left,top; public a_car(int x,int y,String z) { super(x,y,z); left=x; top=y; } public void drawHood(Graphics screen) { screen.setColor(Color.yellow); screen.drawRect(left+20,top-30,50,30); } }//end car class

OVERRIDING EXPLAINED If you have a method in your subclass which has the same name as a method in the parent class, when you create an object of your subclass it will use it's own method. This is called overriding. Examine the code for a_truck and you will see that it has method called paintbody which is also located in the vehicle class. But a_truck’s version of paintbody is slightly different, so when we create an object from a_truck class, it will use the version of paintbody found in a_truck, NOT the one found in vehicle.java.

We are creating a subclass of vehicle. By using the word extends I am saying that car inherits all the methods and variables from the class vehicle

The super command automatically sends the values of x,y, and z to the constructor of the parent(super class) which in this case is vehicle. Vehicle needs these values to draw out the basic picture

We need to localize the x,y values so I can use them in a method below.

A new method which helps draw another part of the car in addition to the basic vehicle. .

Page 148: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 15-OBJECT ORIENTED PROGRAMMING II 133

ADVANCED OBJECT CONSTRUCTION

________________________________________________________________________ Copyright © 2000 Robbie Kailley

CREATING THE TRUCK SUBCLASS Essentially the same ideas presented above. Notice that truck also extends vehicle.java. You can create as many subclasses from a superclass as you desire. A_TRUCK CODE. A CLASS FILE THAT IS A SUBCLASS OF VEHICLE.SHOWS OVERRIDDING Code doesn’t draw anything, it just defines what a truck is. The drawing comes when the

main applet code is created (ex153.java). Notice the paintbody method.

import java.awt.*; //I have created another subclass of vehicle called truck //the ideas are the same as described in comments for the car subclass class a_truck extends vehicle{ int left,top; public a_truck(int x,int y,String z) { super(x,y,z); left=x; top=y; } public void drawFront(Graphics screen){ screen.setColor(Color.blue); screen.drawRect(left+120,top+20,25,30); screen.drawOval(left+130,top+50,10,10); } public void paintbody(Graphics screen,Color clr) { screen.setColor(clr); screen.drawRect(left,top,120,50); screen.drawOval(left+20,top+50,10,10); screen.drawOval(left+45,top+50,10,10); screen.drawString("My truck",left+20,top+20); } }//ends truck class

CREATING THE MAIN APPLET CODE Now, we will create the main applet code that will create some cars and trucks.

Notice that there is no direct declaration of vehicle objects in this program. We only want to create cars and trucks, which derive some of their properties from the vehicle class. This is called information hiding or data abstraction. It's when you "hide" certain code from the main program.

Truck has its own version of paintbody which it will use. It will create a slightly different shape than the paintbody described in vehicle.java

Page 149: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 15-OBJECT ORIENTED PROGRAMMING II 134

ADVANCED OBJECT CONSTRUCTION

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 15.3 THE MAIN APPLET CODE WHICH USES A_CAR AND A_TRUCK Applet draws a truck and a “car”(although not a very pretty one) on the display

import java.awt.*; public class ex153 extends java.applet.Applet { a_car mycar; a_truck mytruck; public void init() { mycar=new a_car(50,50,"A car"); mytruck=new a_truck(200,50,"A truck"); } public void paint(Graphics screen) { setBackground(Color.black); mycar.paintbody(screen,Color.red); mycar.drawHood(screen); mytruck.paintbody(screen,Color.green); mytruck.drawFront(screen); } }//end class

Section 15.3 Mastery Questions

1.Create another subclass of vehicle called RV, which overrides the paintbody method created in vehicle.java and creates a larger square with the wheels closer to both ends of the vehicle. Add an RV object to ex 15.3. 2.Create a subclass of the car class, called police. Its the same as the car except for the blue siren (solid blue rectangle) that’s on the top of the car. Add a police car to ex 15.3.

15.4 SOME NOTES AND TIPS WHEN USING INHERITANCE

You don't have to have all the parents methods and variables available to its subclasses. Table 15.4 Preventing subclassing Steps Example

To prevent variables from being inherited use the private modifier.

private int x,y;

To prevent methods from being inherited use the private modifier.

private void paintbody(Graphics screen) { }

To prevent a class from having any subclasses use the final modifer in front of the class name:

final class car extends vehicle { }

Here I call up the car method and the paintbody method of the car and truck classes. If you look, the car class doesn’t have a paintbody method!! BUT, it inherits the paintbody method from the vehicle class which is its parent class. All the methods and variables of a parent class are available to its subclass(or children) truck has its own

version of paintbody

Page 150: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 15-OBJECT ORIENTED PROGRAMMING II 135

ADVANCED OBJECT CONSTRUCTION

________________________________________________________________________ Copyright © 2000 Robbie Kailley

15.5 FINAL THOUGHTS ABOUT THE INTRODUCTION TO OOP

Well, that’s it for a basic (doesn't seem to basic does it?!) introduction too objects and

the basic theory concerning object oriented programming. There is much more to object design than is described here but a few things to remember are: 1)Design your objects to be independent, self governing units 2)Design objects that will be easily reusable in other programs 3)Make sure to comment the class so another person will know how to implement it in their program.

UNIT EXERCISES

1.Create a class called house which defines a basic house. Create 2 subclasses called chimney_house , and garage_house. In the house class

• The constructor should take in the x,y location of the house

• Create a method which takes in the name of owner of the house. In the garage_class

• create 2 contructors, one that lets the user define the color of the garage, one that only takes in the x,y location of the garage.

Draw at least 2 houses on the screen, one of garage and one of chimney. Add any options your desire. Remember the principles of OOP.

chimney house

garage house

Page 151: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 15-OBJECT ORIENTED PROGRAMMING II 136

ADVANCED OBJECT CONSTRUCTION

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Page 152: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 16-THREADS AND ANIMATION 137

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 16: THREADS AND ANIMATION

UNIT OBJECTIVES:

• 16.1 What is a thread?

• 16.2 How to create Threads in your program to create animation

• 16.3 Reducing Flicker

• 16.4 Using MediaTracker to load images for animation for effectively

16.1 WHAT IS A THREAD?

A thread is used to give the programmer more control of how the program is going to be executed. The programmer can give higher priority to some statements in the program. This way when the program is doing more than one thing at once, it knows which set of statements to give a higher priority to. Basically, you are setting up the structure for how you want your program to multitask. Multitasking is just doing more than one thing at once. You are now able to determine the priority of the multitasking that is going to happen in your program

In this book we will be using simple threads. The thread will be used to create a running applet that can perform an animation forever (like a screen saver or video game). There is no need to create a huge while loop. We can also use threads to pause and restart programs.

16.2 HOW TO CREATE THREADS IN YOUR PROGRAM TO CREATE ANIMATION

As stated above, our programs will have only one thread in this course. We will be using threads to help control our animations. A quick review of the animation steps: To create simple animation in a program, you must follow the basic steps:

• draw the object

• let the person see the object (create a small delay)

• erase the object

• change the coordinates of the object repeat steps over and over again.

Page 153: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 16-THREADS AND ANIMATION 138

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Table 16.2 Using threads in applets to create animation Steps Example

implement the Runnable interface in the program heading line. This built in Java interface contains all the instructions for how to deal with threads.

public class ex162 extends java.applet.Applet implements Runnable{

Declare an object of type Thread Thread runner;

Create a start method. Inside of the start method, initialize the Thread object. Copy the method exactly as it’s shown in the example. What you are doing is checking to see if the thread is active, if it is not, create a new thread.

public void start() { if (runner==null) { runner=new Thread(this); runner.start(); } }

Create a run method which holds the code to execute while the applet is running. This is where you put the instructions you want to repeat while the applet is displaying.

public void run() { while (true) { repaint(); left=left+xmove; try {Thread.sleep(5); } catch (InterruptedException e) { } } }

A try catch statement is used to try some instructions in your program. If it doesn't work, you don't want the program to crash so you "catch" the problem and deal with it. This way your program will not end if there is a problem in dealing with a particular statement/statements. The instructions we are trying to execute is Thread.sleep(5), which enables the program to pause for 5 milliseconds (creating the animation delay).

public void run() { while (true) { repaint(); left=left+xmove; try {Thread.sleep(5); } catch (InterruptedException e) { } } }

create the stop method which will destroy the Thread when the applet is shut off

public void stop() { if (runner!=null) { runner.stop(); runner=null; } }

add the update method to reduce flicker public void update(Graphics screen) { paint(screen); }

while the applet is running, redraw the object,then move the objects coordinates

creates the delay for the animation.You may need to adjust this number depending on the speed of your computer

Creates an infinite loop while applet is running

Lets the built in java function catch and deal with errors when trying to create a delay in the program

Page 154: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 16-THREADS AND ANIMATION 139

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 16.2 SIMPLE ANIMATION USING THREADS Applet draws a red square on a blue background , shows the square moving across the

background.

import java.awt.*; public class ex162 extends java.applet.Applet implements Runnable{ Thread runner; int left; int top; int xmove; public void init() { left=10; top=10; xmove=1; } public void paint(Graphics screen) { screen.setColor(Color.blue);//this refreshes the background screen.fillRect(0,0,400,400); screen.setColor(Color.red);//this draws the red square screen.drawRect(left,top,75,75);//with these coordinates } public void start() { if (runner==null) { runner=new Thread(this); runner.start(); } } public void run() { while (true) { repaint(); //draw the current screen left=left+xmove; try {Thread.sleep(5); } catch (InterruptedException e) { } } } public void stop() { if (runner!=null) { runner.stop(); runner=null; } } public void update(Graphics screen) { paint(screen); } }//ends the main program

Here is the bulk of the program. This is what is run while the thread is active

Adjusting coordinate

You may need to adjust the amount of delay depending on the speed of your computer. If you see the animation is moving too fast, increase the number.

Page 155: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 16-THREADS AND ANIMATION 140

________________________________________________________________________ Copyright © 2000 Robbie Kailley

PAUSING/RESTARTING ANIMATIONS You can also use 2 common method available to threads to pause and restart

programs.

runner.suspend(); //pauses the program runner.resume(); //resumes the program from its paused state

It is common to include buttons in an applet and when the proper button is pressed, the suspend or resume method is called. EXAMPLE 16.2B USING RESUME AND SUSPEND IN AN ANIMATION APPLET Applet shows a square moving across the screen, user can press buttons to stop the

square from moving, and another button will start the square moving again.

import java.awt.*; import java.awt.event.*; public class ex162b extends java.applet.Applet implements Runnable,ActionListener{ Thread runner; int left; int top; int xmove; Button pause,move; String buttonlabel; public void init() { left=10; top=10; xmove=1; pause=new Button("Pause"); move=new Button("Move"); pause.addActionListener(this); move.addActionListener(this); add(pause); add(move); } public void paint(Graphics screen) { screen.setColor(Color.blue);//this refreshes the background screen.fillRect(0,0,400,400); screen.setColor(Color.red);//this draws the red square screen.drawRect(left,top,75,75);//with these coordinates } public void start() { if (runner==null) { runner=new Thread(this); runner.start(); } } public void run() { while (true) {//here is the bulk of the program //this is what is run while the thread is active repaint(); //draw the current screen

Program continued on next page �

Page 156: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 16-THREADS AND ANIMATION 141

________________________________________________________________________ Copyright © 2000 Robbie Kailley

left=left+xmove; try {Thread.sleep(5); } catch (InterruptedException e) { } } } public void stop() { if (runner!=null) { runner.stop(); runner=null; } } public void update(Graphics screen) { paint(screen); } public void actionPerformed(ActionEvent event) { buttonlabel=event.getActionCommand(); if (buttonlabel.equals("Pause")) { runner.suspend(); } if (buttonlabel.equals("Move")) { runner.resume(); } } }//ends ex162b

Section 16.2 Mastery Questions

1.Adjust the first example 16.2 applet so it bounces forever back and forth across the screen.

16.3 REDUCING FLICKER

To reduce the flicker you keep seeing in animation, we can use double buffering. The reason why flicker occurs is that the screen is not able to redraw itself fast enough to fool our eyes into seeing a smooth animation. The trick is to draw everything to an "offscreen" image, which is exactly the same size as the applet. Then when we have finished drawing to the new offscreen image, then we bring the whole image (containing the objects in their new locations) up to the actual applet screen. This reduces flicker tremendously.

Page 157: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 16-THREADS AND ANIMATION 142

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Table 16.3 Creating an offscreen image in applets to reduce flicker Step Example

declare an Image object Image workspace;

declare a new graphics object.(call it offscreen, to make things easier)

Graphics offscreen;

make the image the same size as the applet display. In the init method.

workspace=createImage(400,400);

Link the new offscreen Graphics object to the image we just created. This will make it so when we draw to the offscreen variable, we are actually updating the Image called workspace. Do this in the init method.

offscreen=workspace.getGraphics();

draw everything to the offscreen graphics variable (not the screen variable). In the paint method.

offscreen.setColor(Color.blue); offscreen.fillRect(0,0,400,400); offscreen.setColor(Color.red); offscreen.drawRect(left,top,75,75);

bring the image to the actual screen (using the screen variable now), so the person can now see it. In the paint method.

screen.drawImage(workspace,0,0,this);

EXAMPLE 16.3 DOUBLE-BUFFERING EXAMPLE Applet draws a red square moving across a blue background using double buffering

animation techniques.

import java.awt.*; public class ex163 extends java.applet.Applet implements Runnable{ Thread runner; int left; int top; int xmove; Graphics offscreen; Image workspace; public void init() { workspace=createImage(400,400); offscreen=workspace.getGraphics(); left=10; top=10; xmove=1; } public void paint(Graphics screen) { offscreen.setColor(Color.blue); offscreen.fillRect(0,0,400,400); offscreen.setColor(Color.red); offscreen.drawRect(left,top,75,75); screen.drawImage(workspace,0,0,400,400,this); } public void start() { if (runner==null) { runner=new Thread(this);

Workspace contains all the drawing that was done to the offscreen. Now we are making it visible on the applet display

You don’t need to put 0,0,400,400 because when creating an image the 0,0 is implied

Program continued on next page �

Page 158: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 16-THREADS AND ANIMATION 143

________________________________________________________________________ Copyright © 2000 Robbie Kailley

runner.start(); } } public void run() { while (true) { repaint(); left=left+xmove; try {Thread.sleep(5); } catch (InterruptedException e) { } } } public void stop() { if (runner!=null) { runner.stop(); runner=null; } } public void update(Graphics screen) { paint(screen); } }//ends ex163

16.4 USING MEDIATRACKER TO EFFECTIVELY LOAD IMAGES FOR

ANIMATION

If you are planning to use many images in an applet involving animation, it is a good idea to use the MediaTracker class. This class loads up all the images needed for the applet into memory before the applet begins the animation sequence. This way, the images will be ready to be shown right away when they are needed. If you don’t use this method, sometimes only half of your image will show up during an animation. Table 16.4 Using MediaTracker in image animations Steps Example

create a MediaTracker variable MediaTracker tracker;

create a method where the mediatracker will load up the images (in this example the method is called loadimages)

public void loadimages() { }

call up the loadimages method in your init method

loadimages();

in the load images method, initialize the mediatracker variable.

tracker=new MediaTracker(this);

in the loadimages method, get the picture and load it into the mediatracker, which stores it in memory for use later on.

car=getImage(getCodeBase(), "car1.gif"); tracker.addImage(car,0);

use a try catch statement in the loadimages method to make sure that any errors which occur during image loading in the media tracker are handled by built in functions

try{tracker.waitForAll(); } catch (InterruptedException e) { }

adds the car to the tracker, with an ID number of 0. Since it’s the first picture added

Page 159: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 16-THREADS AND ANIMATION 144

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 16.4 USING MEDIATRACKER TO LOAD IMAGES IN AN ANIMATION Applet draws a car image and a police car image moving across and down the screen.

import java.awt.*; public class ex164 extends java.applet.Applet implements Runnable{ Image policecar,car; MediaTracker tracker; Thread runner; int carleft,policecarleft; int cartop,policecartop; int car_xmove; int policecar_ymove; Graphics offscreen; Image workspace; public void init() { workspace=createImage(400,400); offscreen=workspace.getGraphics(); carleft=10; cartop=10; car_xmove=1; policecarleft=200; policecartop=0; policecar_ymove=1; loadimages(); } public void loadimages() { tracker=new MediaTracker(this); car=getImage(getCodeBase(), "car1.gif"); tracker.addImage(car,0); policecar=getImage(getCodeBase(),"policecar1.gif"); tracker.addImage(policecar,1); try{tracker.waitForAll(); } catch (InterruptedException e) { } }//load images public void paint(Graphics screen) { offscreen.setColor(Color.white); offscreen.fillRect(0,0,400,400); offscreen.drawImage(car,carleft,cartop,30,30,this); offscreen.drawImage(policecar,policecarleft,policecartop,30,30,this); screen.drawImage(workspace,0,0,this); } public void start() { if (runner==null) { runner=new Thread(this); runner.start(); } }

make sure that you have 2 images in your folder before you try to run this program.

load images will be called up first, preparing the images before the animation begins

replace car.gif with the name of your image

redraws the whole background white

draws the car and police car images at their current positions to the offscreen image

draws the whole offscreen image to the actual applet screen

Program continued on next page �

Page 160: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 16-THREADS AND ANIMATION 145

________________________________________________________________________ Copyright © 2000 Robbie Kailley

public void run() { while (true) { repaint(); carleft=carleft+car_xmove; policecartop=policecartop+policecar_ymove; try {Thread.sleep(100); } catch (InterruptedException e) { } } } public void stop() { if (runner!=null) { runner.stop(); runner=null; } } public void update(Graphics screen) { paint(screen); } }//ends ex164

If you are using images in separate class files, using OOP concepts, when you make a call to draw an image in a separate class file from the main applet code, you must use the following rule: screen.drawImage(mypicture,0,0,30,30,null); Here is a basic animation example that uses some simple OOP concepts. Although the animation may not look completely smooth on your screen, you may play around with the Thread.sleep number and also change the xmove number in the constructor call to the car. **You need to have a picture to run this applet, call the picture “car1.gif” or replace car.gif in the following program with the name of your picture** EXAMPLE 16.4B ANIMATION USING OOP CONCEPTS WITH IMAGES Applet shows a car bouncing back and forth across the screen.

import java.awt.*; public class ex164b extends java.applet.Applet implements Runnable{ MediaTracker tracker; Thread runner; Graphics offscreen; Image workspace,pic; car car1;

adjust the left position of the car by the amount of car_xmove.

adjust the top position of the police car by the amount policecar_ymove

paint the cars in their current positions (done in the paint method)

the last parameter has to be null if you are drawing an image in a separate class file using OOP

Program continued on next page �

Page 161: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 16-THREADS AND ANIMATION 146

________________________________________________________________________ Copyright © 2000 Robbie Kailley

public void init() { workspace=createImage(400,200); offscreen=workspace.getGraphics(); loadimages(); car1=new car(pic,10,2); } public void loadimages(){ tracker=new MediaTracker(this); pic=getImage(getCodeBase(),"car1.gif"); tracker.addImage(pic,0); try {tracker.waitForAll(); } catch(InterruptedException e) { } } public void paint(Graphics screen) { offscreen.setColor(Color.white); offscreen.fillRect(0,0,400,200); car1.drawcar(offscreen); screen.drawImage(workspace,0,0,400,200,this); } public void start() { if (runner==null) { runner=new Thread(this); runner.start(); } } public void run() { while (true) { repaint(); car1.checkbounce(); car1.movecar(); try {Thread.sleep(100); } catch (InterruptedException e) { } } } public void stop() { if (runner!=null) { runner.stop(); runner=null; } } public void update(Graphics screen) { paint(screen); } }

Sending the image and the left starting value and starting xmove value to the car. The car knows how to draw itself, and how to move and adjust the bounce.

Calling the method of the car that will draw the car

Calling the checkbounce method of car1 to see if the xmove value needs to be changed.

Adjusting the current coordinates of the car by calling the movecar method which is available to the car

MediaTracker will prelaod images to make animation loading smoother

Program continued on next page �

Page 162: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 16-THREADS AND ANIMATION 147

________________________________________________________________________ Copyright © 2000 Robbie Kailley

class car{ Color clr; Image mypicture; int left,xmove; public car(Image pic,int x,int move){ mypicture=pic; left=x; xmove=move; } public void drawcar(Graphics screen){ screen.drawImage(mypicture,left,10,75,75,null); } public void checkbounce() { if(left<0||left+75>400){ xmove=xmove*-1; } } public void movecar(){ left=left+xmove; } }//ends car class

Unit 16.4 Mastery Questions

1.Add another image to ex 16.4 and make it start in the center of the screen and move diagonally and continue to bounce off the walls. 2.Add another image to ex 16.4b, make it bounce also, but its starting position should be near the right hand side of the applet,moving towards the left. (Hint:make another car object)

UNIT EXERCISES:

1)Adjust the example 16.3 program so the square starts in the middle of the applet screen, and moves diagonally and continually bounces off all the walls. 2)Create a separate class called squares. This calls should contain all the data an object needs to draw and move and bounce itself off the walls. Create 3 different objects of type square in your main applet code. Each should have a different color and a different speed. (These should be taken in through the constructor). Have a pause and restart button. Hint: To use double buffering, you will need to send the offscreen variable to the class for drawing, NOT the screen variable.

Here is where the car class starts

In the constructor we take in the image,x value and the move value

When we draw an image in the class file, the last paramter is not this rather it is null

These 2 methods reverse the value of the xmove variable if the car hits the wall and they adjust the left value of the car by the current xmove value.

Page 163: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 16-THREADS AND ANIMATION 148

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Page 164: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 17-ARRAYS 149

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT 17: ARRAYS

UNIT OVERVIEW

• 17.1 What is an array?

• 17.2 How to create a simple array

• 17.3 Using arrays and Graphics

• 17.4 Using arrays with objects

17.1 WHAT IS AN ARRAY?

An array is a useful way of storing large amounts of data of the same type. (In fact, there are types of arrays that can store data of different types but we will leave that for a future course). For example, assume you want to store the top 10 high scores in a video game. The only way that you know how to do this is to create 10 different integer variables and then assign values to each of them. Not only does this make the variable section in your program cluttered, it will also make your program harder to adjust, because what if you wanted to store the top 100 scores. Could you imagine the size of variable declaration section with 100 integer variables! Also, what if you wanted to find the current high score? The if..then statement to search through the scores would be enormous. Arrays can help solve this problem. They are an effective way to store data and they are the foundation from which a lot of searching and sorting programming code is built upon. You will be using arrays extensively if you are planning on taking higher level programming courses.

17.2 HOW TO CREATE A SIMPLE ARRAY

There are a series of steps used to create arrays. 1. Creating the array variable 2. Initializing the array in the program before giving it any values 3. Assigning values to the array 4. Outputting the array values 1.CREATE THE ARRAY VARIABLE The basic way in which an array is created is that a certain number of spaces in memory are created at the beginning of the program. You can create arrays of any Java type (i.e. integers, doubles, images, and even arrays of objects you have created)

Example int grades[]; //this creates an array called grades. the data type to be stored //in this array will be of type int.

Page 165: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 17-ARRAYS 150

________________________________________________________________________ Copyright © 2000 Robbie Kailley

2.INITIALIZING THE ARRAY IN THE PROGRAM BEFORE GIVING IT ANY VALUES Now before you can start placing values into the array, you have to decide how large the array is going to be. This means, how many different values you will be storing in the array. You indicate this when you actually initialize the array. Example grades=new int[10]; //this initializes the array and indicates the array will have //10 empty spaces where you can place int values One way to think of what you have just created is to imagine that there are 10 spaces in the computer memory which can store int values. grades array

grades[0] grades[1] grades[2] grades[3] grades[4] grades[5] grades[6] grades[7] grades[8] grades[9]

Each space is called an element of the array. Each space is identified by a number called an index. Using the index you can access a particular element in an array. For example grades[1] has an index of 1. grades[9] has an index of 9.

NOTE: the first index of an array is 0. So if you have 10 spaces in an array, the last index will be number 9.

3. ASSIGNING VALUES TO THE ARRAY a)To place values into an array you can assign a value to a particular element of the array.

Example: grades[0] =34; grades[1]=99; grades[5]=100;

Common error #1 if you tried the following you would get an error, because the largest index in the array of 10 spaces is not 10 but 9!! Because the first index is 0. BE CAREFUL WITH THIS. grades[10]=100; Common error #2 grades[8]=10.55; The array is of type int, so if you try to put any other data type in the array, you will get an error.

Page 166: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 17-ARRAYS 151

________________________________________________________________________ Copyright © 2000 Robbie Kailley

b)A common way to fill an array quickly is to use for loops. The for loop variable is also used to determine which index you are currently inputting values into.

Example (using for loops to fill in values for an array) for (int counter=0;counter<10;counter=counter+1){ random_number=(int)(100*Math.random()); grades[counter]=random_number; }

Use the current counter value to determine the index of the current element of the array being used. Then assign it a random number value. For example, if counter is 1 then we would be assigning a value to grades[1]. The when counter changes to 2 as it works its way through the for loop, we would be assigning a value to grades[2]. All the way up to grades[9]. Although it seems we have only input 9 grades, its actually 10 because counter started at 0 (because the first index of an array is zero) and ended at 9. The for loop executes while counter is less than 10, so once the for loop runs through 9, when it gets to 10, it ends the loop because the condition in the for loop is now false (counter<10).

Note: Creating the proper for loop condition is extremely important. If you have an improper for loop you may try to access more indexes than are possible and an error will result.

4.OUTPUTTING VALUES OF AN ARRAY You can output individual array elements if you desire:

Example (assume you have a textfield called output created) output.append(""+grades[5]);

A common way to output values of an array at once is to use a for loop in a similar method as was used to input values. You use the counter variable of the for loop to control the current index of the array being outputted.

Example for (int counter=0;counter<10;counter=counter+1){ output.append("The "+counter+" grade is"+grades[counter]+"\n"); }

gets a random number

this would output the value of whatever is inside the element grades[5]

as the value of counter changes, so does the current grade being output. The first time through the loop grades[0] is output. Then grades[1] is , and so on until grades[9] is output.

Page 167: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 17-ARRAYS 152

________________________________________________________________________ Copyright © 2000 Robbie Kailley

The above snippets of code are combined in a complete example below. In this example an array which contains 10 random grades will be created. The grades will then be output in a textarea. The user will not be give an option to input any scores (although that could be done using textfields, as we will see in example 17.2b.) EXAMPLE 17.2A DECLARING AND USING SIMPLE ARRAYS. Applet adds random numbers to an array and then displays them.

import java.awt.*; public class ex172a extends java.applet.Applet{ int[] grades; TextArea output; int random_number; public void init() { grades=new int[10]; //remember the array actually goes from 0-9 for a total of 10 setLayout(null); output=new TextArea(5,5); output.setBounds(20,20,400,300); add(output); getvalues(); display_values(); } public void getvalues(){ for (int counter=0;counter<10;counter=counter+1){ random_number=(int)(100*Math.random()); grades[counter]=random_number; } } public void display_values(){ for (int counter=0;counter<10;counter=counter+1){ output.append("The "+counter+" grade is"+grades[counter]+"\n"); } } }//ends class

In the above example the user had no chance to input the grades, so in this example, the user will enter in the grades through a textfield and the press of a button. As each grade is entered, the result will be output right away.

Page 168: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 17-ARRAYS 153

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE 17.2B LETTING USER ENTER IN VALUES INTO AN ARRAY Applet lets user enter in values into an array by pressing a button after textfield is full

import java.awt.*; import java.awt.event.*; public class ex172b extends java.applet.Applet implements ActionListener{ int[] grades; TextArea output; int random_number; TextField input; Button submit; String gradeword; int gradenum,currentindex; public void init() { grades=new int[10]; //remember the array actually goes from 0-9 for a total of 10 setLayout(null); output=new TextArea(5,5); output.setBounds(20,120,300,200); add(output); input=new TextField(10); input.setBounds(20,20,100,50); add(input); submit=new Button("Enter Grade"); submit.setBounds(130,20,100,50); submit.addActionListener(this); add(submit); currentindex=0; //starts the index off at 0. } public void actionPerformed(ActionEvent event){ if (currentindex<10) { gradeword=input.getText(); gradenum=Integer.valueOf(gradeword).intValue(); grades[currentindex]=gradenum; output.append("The value for grade "+currentindex+" is "+grades[currentindex]+"\n"); currentindex=currentindex+1; } else { output.append("That's it, the array is full"+"\n"); } } }//ends class

The grade is entered in the array only if the value of currentindex is <10. If the index is 10 or higher then the array is full.

manually incrementing the value of current index by 1.

the current array element is assigned the value of the textfield.

when currentindex is greater than 9, then this message will be printed.

Page 169: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 17-ARRAYS 154

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Section 17.2 Mastery Questions

1.Adjust example 17.2a so that it display the array elements from 9 to 0 (instead of from 0-9) 2.Add another button to example 17.2b, with the label highest grade. When this button is pressed it will print the highest grade that was entered out of the 10 entered. (Hint you will need to use if then to compare the elements of the array to eachother)

SECTION 17.3 USING ARRAYS AND GRAPHICS

We can also use arrays to print out a series of images or even flash through a series of images. To do this we will create an array of images. Then we can use a for loop and run through each of the images. The first thing you need to do is get a few images that you want to sequentially run through. Then you can replace the name of the pictures that I have used with your picture names. The basic rules for creating the array is exactly what we described in the section above. In this case the array will be an array of images. (Find a series of 4-5 pictures showing a cartoon waving in different frames, it looks quite good when you get this working). EXAMPLE 17.3 USING AN IMAGE ARRAY Applet shows a simple animation using 2 pictures in an Image array

import java.awt.*; public class ex173 extends java.applet.Applet implements Runnable{ Image[] picture; Thread runner; Graphics offscreen; Image workspace; int currentpicture; MediaTracker tracker; public void init() { picture=new Image[2]; workspace=createImage(400,400); offscreen=workspace.getGraphics(); loadimages(); currentpicture=1;//this start off so picture #1 will be drawn first } public void loadimages() { tracker=new MediaTracker(this); picture[0]=getImage(getCodeBase(), "T1.gif");

continued on next page�

For information on Mediatracker and Threads, please look at unit 16

Storing pictures in an array, then adding that to the tracker

Page 170: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 17-ARRAYS 155

________________________________________________________________________ Copyright © 2000 Robbie Kailley

tracker.addImage(picture[0],0);

picture[1]=getImage(getCodeBase(),"T2.gif"); tracker.addImage(picture[1],1); try{tracker.waitForAll(); } catch (InterruptedException e) {;} }//load images } public void start() { if (runner==null) { runner=new Thread(this); runner.start(); } } public void run() { while (true) { repaint(); try {Thread.sleep(100); } catch (InterruptedException e) { } } } public void stop() { if (runner!=null) { runner.stop(); runner=null; } } public void paint(Graphics screen){ if (currentpicture==1){ offscreen.drawImage(picture[0],30,30,100,100,this); currentpicture=2; } else { offscreen.drawImage(picture[1],30,30,100,100,this); currentpicture=1; } screen.drawImage(workspace,0,0,this); } public void update(Graphics screen) { paint(screen); } }//ends class

Section 17.3 Mastery Questions

1.Add at least 5 pictures to the array and run through them in a certain order , over and over again.

If the value of currentpicture is 1 then we will draw picture[0] and then change the value of currentpicture to 2 so it will draw a different picture next time.

If currentpicture=2 then draw out picture[1] and then change the value of currentpicture to 1 (otherwise we will keep drawing the same picture over and over again.)

Page 171: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 17-ARRAYS 156

________________________________________________________________________ Copyright © 2000 Robbie Kailley

17.4 USING ARRAYS WITH OBJECTS

It is possible if you have a large number of objects to use an array to keep track of your objects. For example if you have a program that animates 10 cars, instead of declaring 10 separate car objects, we could declare an object array of size 10 of type car. In our example, we will use the car template created in unit 14 and make an array of 5 cars from it. (To look at the car.java template please refer back to unit 14. I will only show how to make an array from that class. The car code is exactly the same as unit 14) Example 17.4 Using arrays with objects a user has created Applet creates 3 cars on the screen.

import java.awt.*; public class ex174 extends java.applet.Applet { car[] mycar; public void init() { mycar=new car[3]; mycar[0]=new car("My car",10,10); mycar[1]=new car("Dad's car",300,10); mycar[2]=new car("Mom's car",10,100); } public void paint (Graphics screen) { mycar[0].getcolor(Color.blue); mycar[1].getcolor(Color.red); mycar[2].getcolor(Color.yellow); mycar[0].drawcar(screen); mycar[1].drawcar(screen); mycar[2].drawcar(screen); } }//ends main applet program

Section 17.4 Mastery Questions

1.For unit 15 unit end exercise, create 5 houses of type chimney using arrays.

Creating the array of car objects

Inititalizing the array of 3 car objects

Actually creating the 3 car objects (using the array)

Calling up methods for each car object. Just as we learned before, put the name of the object, followed by a period and then a method name.

Page 172: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 17-ARRAYS 157

________________________________________________________________________ Copyright © 2000 Robbie Kailley

UNIT EXERCISES

1.Create a simple program which shows an image of a ball rolling across the screen and when it hits the right side of the screen, the ball blows up. Use a series of images stored in array to roll through when showing the ball "blowing up" 2**Hard Question** Using your knowledge of arrays, create a program that will let the user enter in 10 numbers and the program will sort them out from smallest to largest and output the result. (NOTE: to do this program effectively, the sorting code shouldn't be much longer than about 15 lines maximum)

Page 173: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

UNIT 17-ARRAYS 158

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Page 174: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

INTERLUDE-CREATING METHODS 159

________________________________________________________________________ Copyright © 2000 Robbie Kailley

INTERLUDE-CREATING METHODS

UNIT OVERVIEW

• Creating methods to accept variables

• Creating methods which return a value

CREATING METHODS TO ACCEPT VARIABLES

Up until now, all of our method headings have been created using the following format: public void name() { instructions; }//

Now, we will examine why we would want to put something inside the empty round brackets. Quite simply, if you are using a variable from another part of the program, you can choose to “send” that variable to your method. To indicate that your method is waiting for a particular variable, you would put its data-type and name in the round brackets. Although it’s not necessary to do this always (your programs will probably work if you don’t), there are several advantages to doing this.

• You know what variables each method will be using by looking at the heading, this makes it easier to debug

• If someone else is looking at your program, its easier for them to tell how your program is organized

In conclusion, think of the round brackets as the gate-keepers of the method, they

decide what variables are coming in. Try to keep the variables coming in as ones that could be changed. For example, its probably not a good idea to send textfields and textarea through the round brackets because they are unchanging components. Instead, send variables involved in calculations etc.. Table 10.2a Steps in creating method that accept variables Steps Example

create the method with the appropriate heading indicating what variables will be accepted and used by the method

public void printresult(int number1,int total){ output.append("The value of "+number1+" doubled is "+total); }

in the program, when you call up the method, send the appropriate variables

printresult(number1,total);

indicating that printresult will be needing 2 int variables sent to it when it is called

Sending the number1 and total variable to printresult when its called.

Page 175: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

INTERLUDE-CREATING METHODS 160

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE INTER1 SENDING VARIABLES TO METHODS Applet sends 2 variables to the printresult method where the variables are then used.

import java.awt.*; public class inter1 extends java.applet.Applet { int number1,total; TextArea output; public void init() { output=new TextArea(10,30); add(output); docalculation(); //this calls up docalculation method }//ends init public void docalculation() { number1=5; total=number1*2; printresult(number1,total); }//ends docalculation method public void printresult(int number1,int total){ //this method takes in the number1 and total variable, outputs to textarea output.append("The value of "+number1+" doubled is "+total); } }//ends class inter1

You can also send many different variable types, just separate them with commas. EXAMPLE INTER2 SENDING DIFFERENT VARIABLE TYPES TO A METHOD Applet shows a message displaying the results of doubling a number

import java.awt.*; public class inter2 extends java.applet.Applet { String message; int number1,total; TextArea output; public void init() { output=new TextArea(10,30); add(output); docalculation(); //this calls up docalculation method }//ends init public void docalculation() { message="Welcome to the program"; number1=5; total=number1*2; printresult(number1,total,message); }//ends docalculation method public void printresult(int number1,int total,String message){ //this method takes in the total variable and uses it to output in the textarea output.append(message+"\n"+" The value of "+number1+" doubled is "+total); } }//ends class inter2

indicates that printresult will need 2 int variables when its called up. The order in which the variables are sent does matter. It’s expecting number1 first then total

calling printresult and sending 2 variables to it. The order in which the variables are sent matters. Make sure you send them in the order that printresult is expecting them

method is expecting and 2 int variables

and a String variable. In that order

sending the variables to the method in the proper order

Page 176: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

INTERLUDE-CREATING METHODS 161

________________________________________________________________________ Copyright © 2000 Robbie Kailley

CREATING METHODS WHICH RETURN A VALUE

So far, the methods we have created just perform a series of instructions and then end, or call up another method. Sometimes it is useful for a method to figure something out and then return a value. What you do is send the method something, and it performs some calculation and then returns a value.

Example public int square(int number) { int total; total=number*number; return total; }

You can create methods which return any of the variable types we have discussed, just add the variable type to the method heading line.A method can only return one value.

Example public String output() { } this would return a String public double output() { } this would return a double

Table 10.2bCreating method which return a value Steps Example

create the method heading with the proper return type (boldfaced in example)

public int square(int number){ int total; total=number*number; return total; }

inside the method, make sure on the last line, you return a variable of the proper data-type (indicated in the method heading in the previous step) .

public int square(int number){ int total; total=number*number; return total; }

in the program code, create a variable to store the value the method will be returning

int number,finalresult;

You must always assign the method call to a variable when the method returns a value. If you just tried to put the line square(number); in the program, you would get an error.

finalresult=square(number);

int means this method will return an int value

total is a variable that is declared inside the method. Methods can have their own variable declaration section if the variable is used only inside the method and nowhere else in the program. If you do the total declaration inside the method, it is called a local

variable. Local variables can only be used inside the method. Be careful, if you try to use total anywhere else it will cause an error. If you know a variable will be used

in more than 1 method, declare it in the main variable

section at the beginning of the program.

this returns the value of total to wherever the method was called in the program

total is an int variable and it has a value of number*number

will store the result of the method square

assigns the value of square(number) to the variable finalresult

Page 177: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

INTERLUDE-CREATING METHODS 162

________________________________________________________________________ Copyright © 2000 Robbie Kailley

EXAMPLE INTER3 USING METHODS WITH RETURN TYPES Applet uses a method to square a number and return the total. Then the result is

outputted.

import java.awt.*; public class inter3 extends java.applet.Applet { int number,finalresult; String message; TextArea output; public void init() { output=new TextArea(10,30); add(output); getnumber(); //this calls up getnumber method }//ends init public void getnumber() { number=5; finalresult=square(number); output.append("The number "+number+" squared is "+finalresult); }//ends getnumber method public int square(int number){ int total; total=number*number; return total; } }//ends class inter3

UNIT EXERCISES

1.In example inter2, add another method called printname(String name). This method should welcome the user to the program before displaying the results 2.In example inter3, add 2 other methods, one called cubed, one called halved. These methods should return the appropriate number , and then the result should be outputted in the getnumber() method. 3.How many values can a method return? (written answer)

Storing the value of square(number) in a variable called final result

Page 178: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

APPENDIX A-RESERVED WORDS 163

________________________________________________________________________ Copyright © 2000 Robbie Kailley

APPENDIX A-RESERVED WORDS

A.1 LIST OF COMMON RESERVED WORDS

The following is a list of common reserved words in java that you cannot use for

program names, variable names or method names.

abstract default for new super

boolean do if null switch

break double implements package synchronized

byte else import private this

case extends instanceof protected throw

catch false int public throws

char final interface return transient

class finally long short true

continue float native static try

void

volatile

while

Page 179: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

APPENDIX A-RESERVED WORDS 164

________________________________________________________________________ Copyright © 2000 Robbie Kailley

Page 180: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

APPENDIX B 165

________________________________________________________________________ Copyright © 2000 Robbie Kailley

APPENDIX B-SETTING UP JCREATOR AND JAVA ON YOUR PC Everyone must first: 1) Install the Java SDK (SDK stands for Software Developers Kit).This software program contains all the information that java needs to run on your computer. Then you have an option of how you want to type in and run your programs: Recommended: Option 1: Get a free Java IDE (integrated development environment) to run and compile your java programs in a windows environment. Option 2:Run java from DOS or your command prompt if using NT,XP or windows 2000.

GETTING AND INSTALLING THE JDK SDK

Please go to my website http://www3.telus.net/javastarter for the most recent instructions if you are experiencing any problems. Also, feel free to email me for help! STEP 1:

GO to http://www.java.sun.com STEP 2: You want the standard edition of the latest J2SE 1.4.X SDK (x is a number, you want the largest one possible,

i.e. 1.4.1 versus 1.4.2 :The 1.4.2 version is more recent so download that one) The link is usually found under the popular downloads listed on the right side of the page.

STEP 3: 2)When you get to the download page, there are several options as to what you want to download, the program the documentation , new extra’s etc…. You only need to download the basic J2SE v1.4.X , you don’t need anything else bundled with it. Make sure you choose the proper operating system for your computer.

You need to select the SDK (far right column)

GETTING A FREE JAVA EDITOR TO TYPE YOUR PROGRAMS IN A WINDOWS ENVIRONMENT

** At the time of writing this book, the following free editor was available. If it unavailable, just follow the alternative instructions in unit 2 for using notepad and DOS on your computer to run java.

1. Go to http://www.jcreator.com 2. Choose download from the left hand menu 3. Download the freeware version of jcreator.

Page 181: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

APPENDIX B 166

________________________________________________________________________ Copyright © 2000 Robbie Kailley

4. You need to uncompress the file once it is downloaded onto your computer. Use winzip or stuffit or any other compression software to do this.

5. Once it is unzipped, click on the setup icon and follow all the recommended instructions on the screen during the set-up. (Keep clicking on okay until the setup is finished)

6. Jcreator automatically links up to your JDK SDK when it is setting up, so everything is ready to go once Jcreator is setup.

SETTING UP JAVA SDK ON THE MACINTOSH You can download the SDK from http://www.apple.com, once you are at the website, there should be a

link to a site for developers, here you will find the JDK for Macintoshes, it is called the MRJ SDK. Current Website as of printing: http://developer.apple.com/sdk/index.html The name of the link is: Mac OS Runtime for Java 2.2 SDK The MRJ SDK link is about ½ way down the page.

Once you have unstuffed it , you should end up with the following 2 applications in the Java folder.Use finder to find them, and make aliases for them on your desktop. java compiler or javac, and applet applet runner(in the applets folder)

These are the two most commonly used applications for creating and running applets.

Page 182: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

APPENDIX B 167

________________________________________________________________________ Copyright © 2000 Robbie Kailley

USING JCREATOR™

1) Open Jcreator 2) From the file menu, choose new.

3) From the dialog box, make sure the project tab is active and choose an applet

project. Make sure you save the applet project in the proper location, you can switch the save location by pressing the … button.

Page 183: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

APPENDIX B 168

________________________________________________________________________ Copyright © 2000 Robbie Kailley

4) What shows up next is your project. It contains 2 files.

-The .java file is where you will type your code -The .htm file is the webpage that will contain your java applet (java program)

5) Click on the .java icon and examine the file. Jcreator has a default template, with code already in it. Of course you can change the code as you begin to learn Java.

**note jcreator has a slightly different import statement than applets in this book. However, both ways will work fine.

Page 184: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

APPENDIX B 169

________________________________________________________________________ Copyright © 2000 Robbie Kailley

6) Click on the .htm icon. This is a very simple webpage that will load up your Java

program. You can change the size of the Java program by changing the width and height values.

7) TO COMPILE YOUR JAVA PROGRAM, make sure you click on the .java icon

and then when the java code is visible in the main window, click on the build menu and choose compile project.

Page 185: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

APPENDIX B 170

________________________________________________________________________ Copyright © 2000 Robbie Kailley

8) A window will open up on the bottom of the screen, which will display any errors

with your program. If there are no errors, the words Process completed will be shown. This means your program is ready to be run.

9) To actually see the program run, click on the build menu again and this time choose the execute project command.

A new window should appear with your actual Java applet running in it. This window is called the appletviewer and it is one way to see your applet. The other way to see your applet is to open up your Internet browser and open your .htm file of your project.

Page 186: Java Starter - mrkim.2myclass.commrkim.2myclass.com/ict11/java/javastarter/JavaStarter.pdflarger programming questions at the end of every chapter. A disk is provided (if you A disk

APPENDIX B 171

________________________________________________________________________ Copyright © 2000 Robbie Kailley

OPENING EXAMPLE FILES FROM SOLUTIONS DISK USING JCREATOR

The examples and solutions were not created using Jcreator as I cannot assume everyone has that program. If you want to download or view the source of a java applet from the solutions disk usingJCreator follow these steps:

1. Click on the link that lets you view the source. 2. A dialogue box will come up, choose the option that says “save file to disk” 3. After the file is saved, go to it on your computer and open it using jcreator. 4. Jcreator will open the file as a single file, not as a project, so there will be no .htm

file available. NOTE THE NAME OF THE FILE (including capitals), you will be using it in a few steps.

5. Go to the edit menu and choose select all and then choose copy. 6. Go to the file menu and choose new, and create a new applet project with the

same name as the downloaded file. 7. In the new project, open the .java file of the project, and go to the edit menu and

choose select all. 8. Now choose paste from the edit menu. What should happen is the downloaded

file code should now be in the .java code for your project. (You just created a project for the downloaded java file from the solutions disk)

9. Now you can compile and view the applet as per the previous section.