Algoritmiek Variables and Methods Graphics Hoorcollege 10 - Ma. 6 nov. 2006 L.M. Bosveld-de Smet.

Slides:



Advertisements
Similar presentations
COMP 110: Introduction to Programming Tyler Johnson Apr 20, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Advertisements

Custom Painting Gestione della Grafica customizzata Vedi anche:
Applets and Graphics.
Physical Computing INST. Kerem Odabaşı - YTU - Interactive Telecomunication Design Dept.
Rectangles moving and responding to the mouse. We want a window with a pile of rectangles in it When we click a rectangle it changes from filled to unfilled.
JAVA Revision Lecture Electronic Voting System Marina De Vos.
© Vinny Cahill 1 Writing a Program in Java. © Vinny Cahill 2 The Hello World Program l Want to write a program to print a message on the screen.
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
Procedural Programming in C# Chapters Objectives You will be able to: Describe the most important data types available in C#. Read numeric values.
Chapter 15 Graphics. To paint, you need to specify where to paint. Each component has its own coordinate system with the origin (0, 0) at the upper-left.
Copyright 2010 by Pearson Education Building Java Programs More Graphics reading: Supplement 3G.
Copyright 2006 by Pearson Education 1 Building Java Programs Supplement 3G: Graphics.
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Fun with Swing Chapter 9. Overview Swing vs. AWT Creating windows and panels. Displaying formatted text in panels. Drawing graphics (lines, circles, etc.)
Console applicatie static void Main ( ) class Hallo { } { } Console. WriteLine("Hallo " + naam + "!" ); statische methodestatische methoden Console. WriteLine("Wat.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
1 Arrays An array is a special kind of object that is used to store a collection of data. The data stored in an array must all be of the same type, whether.
Made with love, by Zachary Langley Applets The Graphics Presentation.
First BlueJ Day Houston, 2006 David J. Barnes University of Kent.
Web Design & Development Lecture 19. Java Graphics 2.
1 More on Applets Overview l Changing Colors l Changing Fonts & Styles l Applet Life-Cycle l Input using Dialog Window l Input using HTML parameters l.
Frame Windows A frame object is used to create a graphical frame window. This frame is used to show information in a graphical application. The JFrame.
CSE 1341 Honors Professor Mark Fontenot Southern Methodist University Note Set 21.
Chapter 2: Using Objects Part 2. Assume you wish to test the behaviour of some method. This is accomplished by providing a tester class: Supply a main.
Object Oriented Programming one of the main reasons we now teach Java instead of C++. C++ was designed to be backwardly compatible with the original.
Object Oriented Programming one of the main reasons we now teach Java instead of C++. C++ was designed to be backwardly compatible with the original.
The Point Class public class Point { public double x; public double y; public Point(double x0, double y0) { x = x0; y = y0; } public double distance(Point.
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
AWT Components. 2 Using AWT Components 4 Component –Canvas –Scrollbar –Button –Checkbox –Label –List –Choice –TextComponent –TextArea –TextField 4 Component.
Review of Math Class Methods abssqrt minmax powround ceilfloor.
Laboratory Study II October, Java Programming Assignment  Write a program to calculate and output the distance traveled by a car on a tank of.
Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
Graphics Chapter 16.  If you want to draw shapes such as a bar chart, a clock, or a stop sign, how do you do it?
PreAP Computer Science Quiz
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Graphics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Applets Graphical Java programs Run inside web browser Platform-neutral Easy deployment--loads when needed Secure.
Chapter 5 Programming Graphics. Chapter Goals To be able to write simple applications To display graphical shapes such as lines and ellipses To use colors.
Chapter 5 Programming Graphics. Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such.
Graphical User Interface Bonus slides Interaction Between Components & Drawing.
Draw Shapes Introduction to simple graphics. What is a graphics context? An instance of the Graphics class Graphics is ABSTRACT! You can extend Graphics.
Lecture 15.1 Static Methods and Variables. © 2006 Pearson Addison-Wesley. All rights reserved Static Methods In Java it is possible to declare.
Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1.
1 Chapter 15 l Basic Figures l Colors l Fonts and Other Text Details Graphics Objects.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Topics  Applets  Classes used for graphics Graphics Point Dimension.
Slides prepared by Rose Williams, Binghamton University Chapter 19 Swing II.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Java Graphics Applets.
Review CSC 171 FALL 2004 LECTURE 21. Topics Objects and Classes Fundamental Types Graphics and Applets Decisions Iteration Designing Classes Testing and.
Topics AWT Classes Window Fundamentals Working with Frame Windows Creating a Frame Window in an Applet Creating a Windowed Program Displaying Information.
Java applet basics, loading & displaying images After this section, you should be able to : –Use the applet tag and applet parameters –Describe what a.
METHODS AND SCOPE CSCE More on Methods  This is chapter 6 in Small Java.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 6 Graphics.
Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 6 Graphics.
Graphics and Java 2D. 2 Introduction Java’s graphics capabilities –Drawing 2D shapes –Controlling colors –Controlling fonts Java 2D API –More sophisticated.
Chapter 15Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 15 l Basic Figures l Colors l Fonts and Other Text Details.
CSc2310 tutoring session, week 8 Fall, 2012 Haidong(Haydon) Xue 5:30pm—8:30pm 11/27/2012 and 11/28/2012 -Class Members vs Instance Members.
Graphics & Java 2D Drawing Two Dimensional Shapes Controlling Fonts Controlling Colors.
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
BallWorld.java A structured walkthrough. Key Features: 2 classes are created Execution is done through the procedure called “main” which are decleared.
Painting (Chapter 12) Java Certification Study Group January 25, 1999 Mark Roth.
Creating Graphics in Java CSE301 University of Sunderland Harry R Erwin, PhD.
CSI 3125, Preliminaries, page 1 AWT. CSI 3125, Preliminaries, page 2 AWT Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Graphics Chapter 6 Copyright © 2000 W. W. Norton & Company.
The FacebookPerson Example
Graphics Chapter 6 Copyright © 2000 W. W. Norton & Company.
Presentation transcript:

Algoritmiek Variables and Methods Graphics Hoorcollege 10 - Ma. 6 nov L.M. Bosveld-de Smet

Variables: associatie (1)

Variables: associatie (2)

Objects: instance variables instance methods

Voorbeeld Object: letter ‘a’

Classes en Objects

Variables: kenmerken Naam Data Type 8 primitive types onbeperkt aantal object of reference types Bereik (Scope) Levensduur (Lifetime) Initialisatie Declaratie

Variables: verschillende soorten Local variables Parameters Instance variables (non-static fields) Class variables (static fields)

Variables: overzicht kenmerklocal variable / parameter instance variableclass variable plaats van declaratie vòòr gebruik ergens binnen method, constructor of block; in method-declaratie ergens binnen class, maar buiten methods; bij voorkeur private ergens binnen class, maar buiten methods; static en bij voorkeur final gebruik waarde slechts van belang voor method, constructor of block waarde van belang voor object’s state en meerdere methods meestal gebruikt voor constanten zichtbaarheid onzichtbaar buiten method, constructor of block zichtbaar voor alle methods in de class; onzichtbaar voor andere classes zichtbaar voor alle methods in de class; ook zichtbaar buiten de class, als public levensduur start – exit uitvoer van method, constructor of block object-aanmaak met new – verdwijnen van referentie naar object start – exit uitvoer programma

public class variable: voorbeeld Constante van de Math class (java API) public static final double PI = …; public class PrintPI { public static void main (String[] args){ System.out.println(Math.PI); }

Instance variable: voorbeeld public class Bicycle { … … … private int speed; … … … public Bicycle (int startSpeed) { speed = startSpeed; } … … … public int getSpeed (){ return speed; } … … … } instance variable constructor: Bicycle myBicycle = new Bicycle (10); getter method: myBicycle.getSpeed()

public class method: voorbeelden Methods van de Math class (java API) public static int round (float a) public static double sqrt (double a) public static double random () Math.round(5.5)

private class variable / public class method: voorbeelden public class Bicycle { … … … private int speed; private int id; private static int numberOfBicycles = 0; … … … public Bicycle (int startSpeed) { speed = startSpeed; id = ++numberOfBicycles; } … … … public static int getNumberOFBicycles(){ return numberOfBicycles; } … … … } class variable class method: Bicycle.getNumberOfBicycles

local variables: voorbeeld (1) public class Adding { public static void main (String[] args) { int next=1; int total = 0; while (next > 0) { next = Integer.parseInt(SimpleIO.readLine()); total = total + next; } System. out.println("Total is : " + total); }

local variables: voorbeeld (2) while (workToDo (table)) { for (int r = 0; r < table.length; r++) { for (int c = 0; c < table [0].length; c++) { if (table [r] [c] > 3) { stamps += 4; table [r] [c] -= 4;

parameter: voorbeeld public void setFee (double newFee) { fee = newFee; } parameter doc.setFee (150.00);

Array parameters public class WordLists { public static void main(String[] args) String[] wordList1 = {"aap", "hond", "varken", "luipaard", "bever"}; String[] wordList2 = {"hortensia", "roos", "lelie", "geranium", "magnolia"}; System.out.println ("Longest word list 1: " + wordList1[longestWord(wordList1)]); System.out.println ("Longest word list 2: " + wordList2[longestWord(wordList2)]); } private static int longestWord(String[] list) { int indexLongestWord = 0; for (int i = 1; i < list.length; i++) { if (list[i].length() > list[indexLongestWord].length()) { indexLongestWord = i; } return indexLongestWord; }

Instance methods public class Person { private String name; public Person () { name = "no name yet."; } public Person (String initialName) { name = initialName; } public void setName (String newName) { name = newName; } public String getName () { return name; } public void writeOutput () { System.out.println ("Name: " + name); } public boolean sameName (Person otherPerson) { return (this.name.equalsIgnoreCase (otherPerson.name)) }

Class methods: examples public static void callByName (String name) { system.out.print (name); } private static int updateScore (int currentScore, int points) { return currentScore + points; }

Class var./method: gebruik in class public class public static void main (String [] args) { } }

“helpers” Class methods als “helpers” “cohesion” “stepwise refinement” “top-down decomposition”

Verdeling van taken Quiz-programma: Stel een vraag aan de gebruiker Lees het antwoord van de gebruiker Controleer of het antwoord correct is Geef adequate feedback Hou de score bij

Class “helper” methods private static String readAnswer (String question) { SimpleIO.prompt (question); String userInput = SimpleIO.readLine(); return userInput.trim().toLowerCase(); } private static boolean match (String userAnswer, String correctAnswer) { return (userAnswer.equals(correctAnswer)); } private static void giveFeedback (boolean ok, String hurrah, String sorry) { System.out.println (ok ? hurrah : sorry); } private static void updateScore (boolean ok) { if (ok) { score += 10; }

Gebruik van “helpers” in main import jpb.*; public class Quiz { private static int score; public static void main(String[] args) { score = 0; String userAnswer = ""; boolean isCorrect = false; userAnswer = readAnswer ("Waarvan is bit de afkorting?\n") ; isCorrect = match (userAnswer, "binary digit") ; giveFeedback (isCorrect, "Goed geantwoord!", "Sorry. Verkeerd antwoord."); updateScore (isCorrect) ; userAnswer = readAnswer ("Hoeveel bytes komen overeen met 32 bits?\n") ; isCorrect = match (userAnswer, "4") ; giveFeedback (isCorrect, "Het gaat prima zo!", "Wat jammer nu!") ; updateScore (isCorrect) ; System.out.println ("Your total score is " + score + " points."); } }

Graphics

Graphics class of AWT package

DrawableFrame object en methoden import java.awt.*; import jpb.*; public class { public static void main (String[] args) { // create drawable frame DrawableFrame df = new DrawableFrame( ); df.show() / df.setVisible(true); df.setSize(, ); // obtain graphics context Graphics g = df.getGraphicsContext(); //make drawing ; // repaint frame df.repaint(); }

DrawableFrame- en Graphics- objecten graphics context frame / window line

DrawLine class // draws a line inside a frame import java.awt.*; import jpb.*; public class DrawLine { public static void main (String[] args) { // create drawable frame DrawableFrame df = new DrawableFrame("Line"); df.setVisible(true); df.setSize(200,200); // obtain graphics context Graphics g = df.getGraphicsContext(); // draw line g.drawLine(50,50,150,150); // repaint frame df.repaint(); }

Vormen tekenen

Gele achtergrondvorm stoplicht // Draw background of sign g.setColor(Color.yellow) int[] xBackground = {0, 100, 200, 100}; int[] yBackground = {100, 0, 100, 200}; g.fillPolygon(xBackground, yBackground, xBackground.length); X coordinaten van vorm Y coordinaten van vorm kleur van de vorm

5 geneste vierkanten // Draw five nested polygons to form the stripe on the // outer border of the sign g.setColor(Color.black); int[] xPolygon1 = {5, 100, 195, 100}; int[] yPolygon1 = {100, 5, 100, 195}; g.drawPolygon(xPolygon1, yPolygon1, xPolygon1.length); int[] xPolygon2 = {6, 100, 194, 100}; int[] yPolygon2 = {100, 6, 100, 194}; g.drawPolygon(xPolygon2, yPolygon2, xPolygon2.length); int[] xPolygon3 = {7, 100, 193, 100}; int[] yPolygon3 = {100, 7, 100, 193}; g.drawPolygon(xPolygon3, yPolygon3, xPolygon3.length); int[] xPolygon4 = {8, 100, 192, 100}; int[] yPolygon4 = {100, 8, 100, 192}; g.drawPolygon(xPolygon4, yPolygon4, xPolygon4.length); int[] xPolygon5 = {9, 100, 191, 100}; int[] yPolygon5 = {100, 9, 100, 191}; g.drawPolygon(xPolygon5, yPolygon5, xPolygon5.length);

Tekenen van stoplicht // Draw a black rectangle (the traffic signal) g.fillRect(77, 35, 46, 130); // Draw red,yellow,and green circles (the traffic // lights) g.setColor(Color.red); g.fillOval(83, 43, 34, 34); g.setColor(Color.yellow); g.fillOval(83, 84, 34, 34); g.setColor(Color.green); g.fillOval(83, 125, 34, 34);

Tonen van tekst Monospaced, Bold, 30 SansSerif, Italic, 30 Serif, Plain, 40

Toon tekst: programma import java.awt.*; import jpb.*; public class DisplaySum { public static void main (String[] args) { // create drawable frame DrawableFrame df = new DrawableFrame("Wirth's RULE"); df.setVisible(true); df.setSize(350,200); // obtain graphics context Graphics g = df.getGraphicsContext(); // display text in red monospaced bold font g.setColor(Color.red); g.setFont(new Font("Monospaced", Font.BOLD, 30)); g.drawString("DATA STRUCTURES + ", 15, 50); // display text in green sansserif italic font font g.setColor(Color.green); g.setFont(new Font("SansSerif", Font.ITALIC, 30)); g.drawString("ALGORITHMS = ", 15, 100); // display text in blueserif plain font g.setColor(Color.blue); g.setFont(new Font("Serif", Font.PLAIN, 40)); g.drawString("PROGRAMS", 15, 150); // repaint frame df.repaint(); }