430 likes | 652 Views
TCU CoSc 10403 Introduction to Programming (with Java). Java Graphics, AudioClips, Colors, Fonts, and Images. The Graphics Class. The cornerstone of all drawing and graphical user interface (GUI) facilities in Java.
E N D
TCU CoSc 10403 Introduction to Programming (with Java) Java Graphics, AudioClips, Colors, Fonts, and Images
The Graphics Class • The cornerstone of all drawing and graphical user interface (GUI) facilities in Java. • The Graphics class is defined in the java.awt package of the Java API (Application Programming Interface) • The class contains all methods for drawing text strings, lines, and shapes (e.g., rectangles, ovals, arcs, and polygons). • A Java applet that displays graphics does so inside a paint()method – not an init() method. • The methods included in paint()instruct the web browser as to what should be displayed and how and where it should be displayed. • There is an overridable default paint() method (inherited from the JApplet (or Applet) class which in turn inherits them from the java.awt.Component class). The paint() method is automatically invoked by update() when an applet runs (or whenever the applet window is (re)drawn or somehow changes).
The Graphics Class (continued) • Consists of 47 individual and specialized methods for drawing objects. • It is defined in the java.awt package of the Java API (as are almost all classes related in graphics). • awt (pronounced “ought”) stands for abstract windowing toolkit. • In addition to drawing shapes, the Graphics class allows the programmer to also specify whether a shape should be filled and how it should be colored. • The Java coordinate system: Each <x,y> coordinate represents a single pixel. The top-left corner is coordinate <0,0>. All coordinate values are positive. < 0, 0 > + x <x, y> + y
Drawing Text • Text can be drawn on an applet by using the drawString() method inside a paint() method. • The drawString() method requires the text and x and y coordinates to specify where the text should be placed. import java.awt.*; // access the Graphics object import javax.swing.*; // access to JApplet public class DrawEx extends JApplet { public void paint( Graphics g ) { // put your code here! } } Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Coordinates • (0,0) in upper left corner • Consider an Example: import java.awt.*; import javax.swing.*; public class Coords extends JApplet { public void paint( Graphics g ) { g.drawString( "(0,0)", 0, 0 ); g.drawString( "(100,10)", 100, 10 ); g.drawString( "(20,50)", 20, 50 ); g.drawString( "(190,90)", 190, 90 ); } } • Why can’t we see “(0,0)” printed? (0,0) bottom-left is at top of applet and text above it Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Text • To draw text on the applet, we call GraphicsObj.drawString( “text string”, x, y ); import java.awt.*; // access the Graphics object import javax.swing.*; // access to JApplet public class Text1 extends JApplet { public void paint ( Graphics gr ) { gr.drawString ( "Hello Worldling", 0, 0 ); gr.drawString ( "Java rocks", 0, 50 ); gr.drawString ( "Skiing is fun", 50, 50 ); gr.drawString( "To be, or not 2 B", 50, 65 ); } } Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Graphics g The name for the Graphics object in the parameter must match the name of the object when we call drawString public void paint( Graphics grp ) { grp.drawString( "Some text to display", x, y ); } public void paint( Graphics g ) { g.drawString( "Some text to display", x, y ); } grp is the variable name It doesn’t matter what name we use for the variable, as long as we reference the name correctly. g is the variable name Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Java Fonts – some Comments! Java Fonts • Because Java is intended to be a cross-platform language, it can't support all the various font technologies in use on all computers. • Instead, Java supports just 5 fonts which will be available on most computers that have a Java-enabled browser or the Java Development Kit installed: these are Dialog, Helvetica (SanSerif), Courier (monospaced), TimesRoman (Serif), and the less useful DialogInput. • Although applets will still display text if you enter something different into their Font parameters, they will do so by using the default font. In most applets, the default font is either Dialog or Helvetica.
The Font Class • The Font class provides methods for specifying the fonts used in a program. (A font defines the distinct look of each character when it is printed or drawn). • Fonts are encapsulated (contained) in the java.awt package. Note: when the font is applied to an object (either graphic or component), the text will appear using that font face. • The constructor for the Font class is: Font (String name, int style, int size); where: The name parameter specifies the name of the desired font (must be one of the valid system fonts). The style parameter should be chosen from one of the static constants (Font.PLAIN, Font.BOLD, or Font.ITALIC). The size parameter refers to the point size of the font. • Examples: (1) Font myFont; myFont = new Font(“Courier”,Font.BOLD,16); or (2) Font myFont = new Font(“Courier”,Font.BOLD,16);
The Font Class (continued) • Font names can be chosen from: Java Namev.1.1 Name Change HelveticaSansSerif TimesRomanSerif CourierMonospaced Dialog DialogInput • Examples: Font title = new Font(“Serif”,Font.PLAIN,16); Font heading = new Font(“SansSerif”,Font.BOLD+Font.ITALIC,30); cancelB.setFont(title); labelL.setFont(heading);
Font Example import javax.swing.*; import java.awt.*; public class FontDemo extends JApplet { Font title; //instantiated below Font subHeading = new Font("Serif",Font.BOLD,20); Font heading = new Font("SansSerif",Font.BOLD+Font.ITALIC,30); public void paint(Graphics here) { title = new Font("Serif",Font.ITALIC,16); here.drawString("COSC 10403", 10,30); here.setFont(title); here.drawString("COSC 10403", 10, 75); here.setFont(subHeading); here.drawString("COSC 10403", 10, 125); here.setFont(heading); here.drawString("COSC 10403", 10, 175); } }
The Color Class • Colors can be set using the setBackground() and setForeground() methods from the Componentclass and setColor() from the Graphics class. • Colors are composed of a red, green, and blue component, each of which is represented by a value in the range 0 [none of the component] to 255 [all of the component]. The standard RGB model. • The syntax to use one of the 13 standard pre-defined colors is:graphics_obj_name.setColor(color_object) Predefined colors: • For example: Using the standard qualified color constants, we could write the following statement (assuming that cancelB is an instance of the Java Button class) – cancelB.setBackground(Color.blue); cancelB.setForeground(Color.RED); or g.setColor(Color.YELLOW);
Color Example import java.awt.*; import javax.swing.*; public class ColorEx extends JApplet { public void paint ( Graphics g ) { g.setColor( Color.RED ); g.drawString( "My favorite color", 30, 45 ); g.setColor( new Color( 12,34,52)); g.drawString( "Can't wait to ski again", 30, 53 ); } } Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Constructors • What would we do if we wanted to use a color other than one of the 13 predefined ones? • Can new colors be created by changing the RGB values? • Yes - but in order to do so, a new color must be defined with the desired RGB values. • This is done using the class’“constructor”. • Constructors are very important parts of most class definitions. • A class’ constructor is invoked when a new object of that type is needed.
The Color Class (continued) • In addition to the predefined colors, we can create many other specific colors in a Java program. • The object constructor for the Color class is: Color (int red_val, int green_val, int blue_val); Where argument values are in the range 0 to 255! • To construct a new Color object, one must first declare a new Color object - syntax: Color myColorName; • Secondly, the new Color object must be constructed – syntax:myColorName = new Color(r,g,b); Example: (1) Color myColor; myColor = new Color(255,0,128); //fuchsia???? cancelB.setForeground(myColor); or (2) Color myColor = new Color(255,0,128); cancelB.setForeground(myColor);
Rectangles Demo import java.awt.*; import java.applet.Applet; // Draws various types of rectangles. public class Rectangles extends Applet { public void paint( Graphics g ) { // draws regular shaped rectangles g.drawRect(20,20,30,50); //tall, thin rectangle g.drawRect(70,40,60,10); //long, thin rectangle g.drawRect(150,30,30,30); //a square g.fillRect(30,100,50,30); //a filled rectangle g.fillRect(100,100,20,40);//another filled rectangle //draws rounded corner rectangles g.drawRoundRect(30,150,30,40,20,20); g.fillRoundRect(30,200,30,40,10,10); //should draw 3 dimensional rectangles g.draw3DRect(30,250,30,40,true); //raised g.draw3DRect(30,300,40,30,false); //lowered } //end of method paint } // end of class Rectangles
Arc Example import javax.swing.*; import java.awt.*; public class PieChart extends JApplet { public voidpaint( Graphics g ) { // pie g.setColor( Color.red ); g.fillArc( 20,20, 300, 300, 20, 90 ); g.setColor( Color.yellow ); g.fillArc( 20,20, 300,300, 110,45 ); g.setColor( Color.blue ); g.fillArc( 20,20, 300,300, 155, 180 ); // outline g.setColor( Color.black ); g.drawArc( 20,20, 300, 300, 0, 360 ); } } Drawing the outline has to be done last – Why? To overlay it on top of color pies Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Polygons & Polylines • The Graphics class also includes methods for drawing polygons and polylines. These methods permit the drawing of figures such as -
Polygon • Add as many points as we want • Order is important – like connect-the-dots • For example: Polygon poly; poly = new Polygon( ); poly.addPoint( x, y ); . . . //code to add other points • x and y are the x and y coordinates for the point. • Draw a polygon: g.drawPolygon( poly ); g.fillPolygon( poly ); Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Polygon import javax.swing.*; import java.awt.*; public class PolyEx2 extends JApplet { public void paint( Graphics g ) { Polygon pg = new Polygon( ); pg.addPoint( 10, 10 ); pg.addPoint( 50, 100 ); pg.addPoint( 10, 30 ); pg.addPoint( 50, 10 ); pg.addPoint( 70, 80 ); g.drawPolygon( pg ); } } import javax.swing.*; import java.awt.*; public class PolyEx1 extends JApplet { public void paint( Graphics g ) { Polygon pg = new Polygon( ); pg.addPoint( 10, 10 ); pg.addPoint( 50, 10 ); pg.addPoint( 70, 80 ); pg.addPoint( 50, 100 ); pg.addPoint( 10, 30 ); g.drawPolygon( pg ); } } The order of adding points is important! Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Nested Squares Demo /*************************************************** This is a sample applet for trying some of the Graphics methods. It draws a sequence of three squares with increasing sizes and border thicknesses. ****************************************************/ import java.applet.*; import java.awt.*; public class SquaresDemo extends Applet { public void paint( Graphics g ) { // Draw the first square. g.drawRect(50,80,100,100); // Draw the next square, offset from the first // by 25, 50 pixels larger, with line width 2. g.drawRect(75,105,150,150); g.drawRect(76,106,148,148); // Draw the last square, offset from the second // by 25, 50 pixels larger, with line width 3. g.drawRect(100,130,200,200); g.drawRect(101,131,198,198); g.drawRect(102,132,196,196); } }
Another Nested Squares Demo public class Logo2 extends Applet { public void paint( Graphics g ) { int x = 50; // x coord. of first square int y = 80; // y coord. of first square int size = 100; // size of first square int OFFSET = 25; // x, y offsets of squares int INCREMENT = 50; // size increase of squares // Draw the first square. g.drawRect(x,y,size,size); // Increment the start coordinates and size // and draw a border-width-2 square. x = x + OFFSET; y = y + OFFSET; size = size + INCREMENT; g.drawRect(x,y,size,size); g.drawRect(x+1,y+1,size-2,size-2); // Do it again, for the third square x = x + OFFSET; y = y + OFFSET; size = size + INCREMENT; g.drawRect(x,y,size,size); g.drawRect(x+1,y+1,size-2,size-2); g.drawRect(x+2,y+2,size-4,size-4); } }
Consider Another Example //No_Parking sign import java.awt.*; import java.applet.Applet; public class No_Parking extends Applet { public void paint( Graphics g ) { g.drawString("Parking",50,50); g.drawOval(45,24,43,43); g.drawLine(82,30,51,61); } // end of method paint } // end of class No_Parking
Consider Another Example //Smiley face import java.awt.*; import java.applet.Applet; public class SmileyFace extends Applet { public void paint(Graphics g) { resize(300,300); g.setColor(Color.yellow); g.fillOval(50,50,200,200); g.setColor(Color.black); g.drawOval(50,50,200,200); g.drawOval(51,51,198,198); g.fillOval(110,110,10,10); g.fillOval(175,110,10,10); g.drawArc(115,160,70,50,-20,-140); g.drawArc(114,160,70,50,-20,-140); g.drawArc(113,160,70,50,-20,-140); g.drawArc(112,160,70,50,-20,-140); } }
getCodeBase( ) determines where your files are, no matter if using Windows, Mac, Linux or on the Internet! Images • Call method getImage Image imageVariable = getImage( getCodeBase( ), filename ); • Graphics method drawImage Needs the keyword this g.drawImage( imageVariable, x, y, this ); // scale the image: d:destination, s:source image g.drawImage(imageVariable, xd1, yd1, xd2, yd2, xs1, ys1, xs2, ys2, this ); • getCodeBase( ) determines the location of your files: • Eg. Windows: C:\Documents and Settings\username\Desktop\java • E.g. Linux: \usr\home\username\java • Eg. Internet: http://stuwww.tcu.edu/~username/Lab1.bin Top left of the destination Bottom right of the destination Top left of the source Bottom right of the source Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Image Example import javax.swing.*; import java.awt.*; public class ImageEx extends JApplet { public void paint( Graphics g ) { Image img = getImage( getCodeBase( ), "Lion.jpg" ); g.drawImage( img, 0,0, this ); } } Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Image Example import javax.swing.*; import java.awt.*; public class ImageEx extends JApplet { public void paint( Graphics g ) { Image img1 = getImage( getCodeBase( ), "Pics/Tiger.jpg" ); g.drawImage( img1, 0,0, this );//original picture g.drawImage( img1, 0, 0, 100, 150, 0, 0, 500, 600, this ); } } <0,0> Destination Dimensions Source Dimensions <100,150> ** Note: the picture is 500 pixels x 600 pixels.
Another Image Example import javax.swing.*; import java.awt.*; public class ImageEx extends JApplet { Font largeFont = new Font("SansSerif",Font.BOLD,15); Font smallFont = new Font("SansSerif",Font.ITALIC,10); public void paint( Graphics g ) { Image img1 = getImage( getCodeBase( ), "Pics/Tiger.jpg" ); g.drawImage( img1, 0,0, this ); g.setFont(largeFont); g.drawString("Unscaled Image", 275, 450); g.drawImage( img1, 0, 0, 100, 150, 0, 0, 500, 600, this ); g.setFont(smallFont); g.drawString("Scaled Image", 10, 140); } } ** Note: the picture is 500 pixels x 600 pixels.
Image format types • Web supports 3 major formats: • .jpg or .jpeg • Joint Photographic Experts Group • Supports 24-bit colors (2^24 number of colors) • Best on photographs, naturalistic artwork types • NOT good on lettering, simple cartoons, B/W line drawings • Uses compression algorithm that can cause loss of detail (lossy) • .gif • Graphics Interchange Format • 8-bit color (supports at most 256 colors) • Not good for photographs or realistic artwork • OK for lettering and simple sketches (lossless) • Supports transparency and animation • .png • Portable Network Graphics • Created as a free compression algorithm when gif became patented • Better compression than .gif – resulting in smaller file sizes • Supports millions of colors • Supports transparency but not animation • Not supported by all browsers Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Image types – Why care? • Some support features that others don’t (animation, transparency, greater number of colors, etc.) • Can drastically change size of the file • Increase loading speed • Decrease space used to store image on web server • Desirable file sizes • 50-300k approx • Decreasing the file size of an image • Shrink image size • Use different compression (gif/jpg/png)s info from: http://webmaster.ucr.edu/presentations/images.ppt Slide created by: Professor Elizabeth Boese, “An Introduction to Pogramming with Java Applets”, Jones and Bartlett Publishers.
.gif is not as good since the 256 color pallet is inadequate and the image is “dithered”. ,jpeg looks better .jpg vs .gif .gif is good since the 256 color pallet is adequate. ,jpeg loses some detail in the compression.
jpeg compression experiment http://www.cs.sfu.ca/CourseCentral/365/li/material/cgi-bin/whichjpeg.cgi Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Image size • Terminology • ppi = pixels per inch (for screen display) • dpi = dots per inch (for printing) • Java • There are ways to scale and modify images within java, but gets very complex • Easier to modify image in a graphics program instead Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Pixels • Pixels are small rectangular areas on the screen that hold a solid color. • More pixels means better quality of the image – less ragged Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Modifying Images - Programs • Microsoft Paint • Photoshop • PaintShopPro • Gimp • Programs that came with your digital camera and/or printer Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Image size • Images on the Web/applet should fit within the screen or area where you want it. • Digital cameras and photos shops usually return images to you at 1600x1200 – really large! • 640x400 pixels is probably the biggest size you’d want, or even smaller • To see the size of your image in MS Paint, Click on Image - then Attributes Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Anti-Aliasing • Anti-aliasing helps smooth the lines. • Works on both graphics and text • Can slow-down drawing process • To use anti-aliasing, need to convert Graphics object to Graphics2D public void paint( Graphics grph ) { Graphics2D g2d = (Graphics2D)grph; g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); // now draw your code with // g2d.drawRect, etc. } Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
AudioClips • Java will allow you to input an audioClip which can then be played in your applet. • AudioClips that can be played: • .au (recorded at 8 KHz, mono, in mu-law encoding) • other formats: .wav & .mid & .mp3??? • Operations that can be preformed: • audioClipFileName.play(); • audioClipFileName.loop(); • audioClipFileName.stop();
Reading in AudioClip(s) public class PlayAudio extends Applet { AudioClip clip1, clip2; // Place the woof.wav and bark.wav audioClips in a folder // (labeled Sounds) in the project’s bin folder. public void init() { clip1 = getAudioClip(getCodeBase(), “Sounds/woof.wav"); clip1.play(); } public void paint() { clip2 = getAudioClip(getCodeBase(), “Sounds/bark.wav"); clip2.loop(); } }