Download TCU CoSc 10403 Programming with Java

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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
import
java.awt.*;
// access the Graphics object
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 );
}
}
•
(0,0) bottom-left is
at top of applet and
text above it
Why can’t we see “(0,0)” printed?
5
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.*;
import javax.swing.*;
// access the Graphics object
// 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 );
}
}
6
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
grp is the
variable name
public void paint( Graphics grp )
{
grp.drawString( "Some text to display", x, y );
It doesn’t matter what
name we use for the
variable, as long as we
reference the name
correctly.
}
public void paint( Graphics g )
{
g.drawString( "Some text to display", x, y );
}
g is the variable
name
7
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)
or
Font myFont
(2)
Font myFont;
myFont = new Font(“Courier”,Font.BOLD,16);
= new Font(“Courier”,Font.BOLD,16);
The Font Class (continued)
• Font names can be chosen from:
Java Name
Helvetica
TimesRoman
Courier
Dialog
DialogInput
v.1.1 Name Change
SansSerif
Serif
Monospaced
• 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
{
Font
Font
Font
class FontDemo extends JApplet
title; //instantiated below
subHeading = new Font("Serif",Font.BOLD,20);
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",
here.setFont(title);
here.drawString("COSC 10403",
here.setFont(subHeading);
here.drawString("COSC 10403",
here.setFont(heading);
here.drawString("COSC 10403",
}
}
10,30);
10, 75);
10, 125);
10, 175);
The Color Class
•
Colors can be set using the setBackground() and setForeground() methods
from the Component class 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:
Color
Color Object
RGB Value
Using the standard qualified color
constants, we could write the
following statement (assuming
that cancelB is an instance of the
Java Button class) –
black
Color.black, Color.BLACK
(0, 0, 0)
blue
Color.blue, Color.BLUE
(0, 0, 255)
cyan
Color.cyan, Color.CYAN
(0, 255, 255)
gray
Color.gray, Color.GRAY
(128, 128, 128)
dark gray
Color.darkGray, Color.DARKGRAY
(64, 64, 64)
light gray
Color.lightGray, Color.LIGHTGRAY
(192, 192, 192)
cancelB.setBackground(Color.blue);
cancelB.setForeground(Color.RED);
green
Color.green, Color.GREEN
(0, 255, 0)
magenta
Color.magenta, Color.MAGENTA
(255, 0, 255)
orange
Color.orange, Color.ORANGE
(255, 200, 0)
pink
Color.pink, Color.PINK
(255, 175, 175)
red
Color.red, Color.RED
(255, 0, 0)
white
Color.white, Color.WHITE
(255, 255, 255)
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 );
}
}
13
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:
Example: (1)
or
myColorName = new Color(r,g,b);
Color myColor;
myColor = new Color(255,0,128);
cancelB.setForeground(myColor);
(2)
//fuchsia????
Color myColor = new Color(255,0,128);
cancelB.setForeground(myColor);
Drawing Shapes
• Rectangles
drawRect (int x, int y, int width, int height)
fillRect (int x, int y, int width, int height)
clearRect (int x, int y, int width, int height)
drawRoundRect (int x, int y, int width, int height, int arc_width, int arc_height)
fillRoundRect (int x, int y, int width, int height, int arc_width, int arc_height)
draw3DRect ( int x, int y, int width, int height, boolean raised)
fill3DRect ( int x, int y, int width, int height, boolean raised)
Notes:
(1) the first two parameters indicate the <x , y> coordinate o f the upper-left corner of the
rectangle.
(2) In the case of a rounded rectange, the <x, y> coordinate indicates the upper-left corner of
the bounding rectanges – the same is true for ovals.
(3) The third and fourth parameters represent the width and height of the rectangle in pixels.
(4) The drawRect and fillRect methods draw unfilled and filled rectangles in wha tever the
foreground color is.
(5) The clearRect method draws a rectangle in the current background color (effectively
erasing it).
(6) The last two methods draw rectangles with slight 3-dimensional effects. If last parameter is
true – shading is raised, false – shading is lowered.
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
Lines
//draws a line between the points (x1,y1) and (x2,y2)
• drawLine(int x1, int y1, int x2, int y2)
Strings
//draws the given text on the screen
• drawSring(String str, int x, int y)
Ovals
//draw filled and unfilled ovals
• drawOval(int x, int y, int width, int height)
• fillOval(int x, int y, int width, int height)
Arcs
//draw segments of ovals
• drawArc(int x, int y, int width, int height,
int start_angle, int arc_angle)
• fillArc(int x, int y, int width, int height,
int start_angle, int arc_angle)
Other Shapes
import java.awt.*;
import java.applet.Applet;
public class OtherShapes extends Applet
{
public void paint( Graphics g )
{
//draw and label a line from <20,20> to <40,50>
g.drawLine(20, 20, 40, 50);
g.drawString("<20,20>", 0, 18 );
g.drawString("<40,50>",25,60);
//draw some ovals
g.drawOval(10,80,30,50); //not filled
g.fillOval(50,80, 50,30); //filled
g.drawOval(120,80,25,25); //a circle
//draw some arcs
g.drawArc(10,150,60,30,20,90);
g.drawArc(50,150,30,70,-180,180);
g.fillArc(10,250,60,30,20,90);
g.fillArc(10,300,50,50,45,270);
} //end paint class
} //end OtherShapes class
drawArc() Method
Arc Example
Drawing the outline
has to be done last –
Why?
To overlay it on top of
color pies
21
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 );
23
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 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 );
}
}
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 );
}
}
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);
}
}
Images
•
Call method getImage
Image
•
imageVariable
=
getCodeBase( ) determines
where your files are, no
matter if using Windows,
Mac, Linux or on the
Internet!
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 );
Top left of the
destination
• getCodeBase( )
– Eg. Windows:
– E.g. Linux:
– Eg. Internet:
Bottom right of
the destination
Top left of the
source
Bottom right of
the source
determines the location of your files:
C:\Documents and Settings\username\Desktop\java
\usr\home\username\java
http://stuwww.tcu.edu/~username/Lab1.bin
29
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.
30
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 );
}
}
Destination Dimensions
<0,0>
Source
Dimensions
<100,150>
** Note: the picture is 500 pixels x 600 pixels.
31
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.
32
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
33
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.
34
.jpg vs .gif
.gif is not as good since the 256 color pallet
is inadequate and the image is “dithered”.
,jpeg looks better
.gif is good since the 256 color
pallet is adequate.
,jpeg loses some detail in the
compression.
35
jpeg compression experiment
http://www.cs.sfu.ca/CourseCentral/365/li/material/cgi-bin/whichjpeg.cgi
36
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
37
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
38
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
39
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
40
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.
}
41
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();
42
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();
}
}
43