70 likes | 86 Views
Learn how to draw shapes, lines, and text using Java's Graphics class. Explore different methods and create your own creative drawings. Step-by-step instructions provided.
E N D
Please open JCreator and follow these steps: • Configure Options • JDK Tools • Choose Run Applet from drop-down • Click Default, then Edit • Click the 3 dots next to the Command box, then go to D Drive (Temp Local Storage) Java software jdk1.7.0_45 bin, then double-click appletviewer. • OK, then Apply, then OK
Intro to Graphics • Graphics are often created using an applet • An applet is simply a Java program that is embedded in an HTML document, and (usually) is designed to be Web-accessible • You must compile an applet file before embedding it in an HTML file (the HTML file only takes the bytecode, which can then be run using any browser – this is one of Java’s major advantages over other languages) • Applet files… • Have no main • Import 2 or more packages • Must extend the class called Applet • Once embedded, can be viewed with a browser or appletviewer
To draw graphics, define the paint method that is inherited from Applet • The paint method accepts one parameter, of type Graphics • Using the Graphics object, you can draw using methods such as drawRect( ), drawOval( ), drawLine( ), etc. • Java uses an xy-coordinate system, with the top-left corner being the origin (0,0) • When drawing shapes, you pass parameters specifying where to begin the shape, and how far to draw it. • Example: page.drawRect(100,100,80,50) /* draws a rectangle starting at (100,100) and with length=80 and height=50. page is the Graphics object */ • Demo….GraphicsDemo
To draw a line: drawLine(startX,startY,endX,endY) // note how this is different from rectangles! • Demo… • To draw an oval, you specify the dimensions of its bounding rectangle, the rectangle that it would fit into • To draw a circle: the bounding rectangle must have equal sides (a square) • Demo… • To draw an arc (part of a circle): like drawing an oval, but also give the starting angle and the measure of the angle • Demo…
To write text: drawString(String,x,y) // x,y is bottom left with Strings!! • Demo…. • The Color class has a bunch of predefined colors, such as Color.yellow and Color.red • You can set the background by simply typing setBackground(Color), but to set a shape’s color, you must use the Graphics object (i.e. page.setColor(Color.Blue) ) • Demo: Snowman
When creating the HTML documents for your assignments, it is easiest to create a New HTML Document, then copy the code from Graphics.html, then change the “______.class” and the width and height. • Very important – you must save your .java and .html files in the same folder!
Assignments • Make sure you save all graphics assignments in your Unit 5 Assignments folder. • P. 118 # 14 (call it P118num14) • P. 118 # 15 • (Drawing1) Create a drawing of your own – be creative, and experiment with all of the methods of the Graphics class that we learned.