0% found this document useful (0 votes)
31 views29 pages

Java Graphics Programming Basics

MySQL

Uploaded by

ms4741100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views29 pages

Java Graphics Programming Basics

MySQL

Uploaded by

ms4741100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Outline

 Introduction.
CSE 201  Graphics Contexts and Graphics Objects.
 Color Control.
INTRODUCTION TO COMPUTING II  Font Control.
 Drawing Lines, Rectangles and Ovals.
CHAPTER – 18  Drawing Arcs.
 Drawing Polygons and Polylines.
GRAPHICS IN JAVA
 The Java 2D API (Application Programming Interface).
 Java 2D Shapes.
1 2
Introduction to Computer Graphics Cont…
• Computer graphics: generating 2D images of a 3D world Applications of
represented in a computer. Computer Graphics
1. Entertainment: Entertainment
• Main tasks in Graphics:

The Visible Human Project


animated movies, etc.
• modeling: (shape) creating and representing the geometry of
objects in the 3D world. 2. Medical Visualization
• rendering: (light, perspective) generating 2D images of objects. 3. Educational Training Training
• animation: (movement) describing how objects change in time. 4. Game Modeling &
• Representations in Graphics: Simulation
Medical
• Vector Graphics: Image is represented by 5. Graphical User Interfaces Visualization
continuous geometric objects: lines, curves,
etc. E.g., PowerPoint, CorelDraw, SVG, ... (GUI)
• Raster Graphics: Image is represented as 6. Computer Aided Design
a rectangular grid of colored pixels… generic
& realistic images. E.g., Paint, PhotoShop, ... (CAD)
y-axis (512, 384, Games & Simulation
0)
7. Scientific Visualization
• Coordinate System : x-axis
CAD
• World Coordinates: Center is (0,0) z-axis (512, -384, 0)
• Screen Coordinates: Upper-left corner is (0,0) (0, 0, 0) in world coordinates
(512,384,0) in real coordinates
3 •… Scientific
Visualization
GUI 4
Cont… Cont…
Other tasks in Graphics: Edge • Using the Graphics Class in Java
• Image processing techniques Detection • paint() or paintComponent() is passed a reference
• Edge Detection to a Graphics object.
• Image De-noising Image • A Graphics object is a device-independent interface to the
• Object Detection De-noising
computer's graphics display.
•…
• Geometric Transformations • Most of its methods are concerned with drawing shapes
• Translation: moving an item from one location to (filled and unfilled), and managing fonts and colours .
another, e.g., moving thru a room or landscape. Translation
• paint() or paintComponent() sends Graphics object:
• Rotation: changing the orientation of an item at a • the drawOval() message, to draw each point .
given location, e.g., spinning around. • the drawLine() message, to draw the straight line .
• Scaling: changing the size of an item as it appears
on screen, e.g., item gets larger or smaller. Rotation
• Some Graphics Methods:
• Clipping: knowing where to stop drawing an item • drawString()
because it partially extends beyond the screen. • drawOval(), fillOval()
• drawRect(), fillRect(), clearRect()

Scaling
drawRoundRect(), fillRoundRect()
• More advanced operations: Hidden surface • draw3DRect(), fill3DRect()
algorithms, Representing 3D shapes, Displaying depth • drawArc(), fillArc()
relationships, Shading, reflection, ambient lighting.. etc… • drawPolygon(), fillPolygon()
5 • drawPolyline() 6
Cont…
• Put your own graphics on the screen:
1. Create your own paintable widget Make a subclass of JPanel, a widget
that can be added to a frame, and
2. Put the widget on the frame override the paintComponent() method
3. Display it g is a Graphic object; actual drawing
--------------------------------------------
surface that mapped to the real display,
import [Link].*; and is handed to you by the system
import [Link].*;
class MyDrawPanel extends JPanel { paintComponent() or paint() is called
Graphics
public void paintComponent(Graphics g) {
[Link]([Link]);
by system when painting the widget

Draw a rectangle with orange color


In
[Link](20,50,100,100);
} Java
public static void main(String[] args) {
MyDrawPanel dP=new MyDrawPanel();
JFrame jF = new JFrame("Graphics");
[Link](dP);
[Link](250,250);
[Link](true);
}
}

Example-1: Draw a rectangle in orange color 7 8


Graphics Context and Objects Cont…
• A GUI component is an object that can be represented
visually on the computer screen and can be acted upon • [Link] is the abstract superclass for
by a human user. all graphics context objects in Java. You can use its
• Examples: windows, buttons, combo boxes, scroll bars, etc. methods to get and set the data within a graphics
• In Java, such an object must be an instance of the class context.
[Link] or its many subclasses. • Enables drawing on screen. Has methods for drawing, font
manipulation, etc.
• Rendering is the process of transforming the GUI • Graphics is an abstract class!
component’s internal data into a visual image. • Cannot instantiate objects.
• In Java, a graphics context object holds the data needed to • Implementation hidden - more portable.
do this transformation. Such data includes:
• The component’s color.
• The component’s font.
• The transform mapping is used to convert component
coordinates into pixel positions on the display device.
9 10
Cont… Color Control
• The Component Class •Class Color
• Superclass for many classes in [Link] package • Defines methods and constants for manipulating colors.
• Method paint() takes Graphics object as an argument. • Colors created from red, green, and blue (RGB) components.
• RGB value:
• paint()often called in response to an event.
• 3 integers from 0 to 255 each, or 3 floating point values
• repaint()calls update(), which forces a paint() from 0 to 1.0 each.
operation. • Larger the value, more of that color.
• update() rarely called directly!
• Color methods getRed(), getGreen(), getBlue()
• Sometimes overridden to reduce "flicker"
Headers:
return an integer between 0 and 255 representing
public void repaint() amount.
public void update(Graphics g)
• Graphics method setColor() takes Color object
and sets the drawing color.
• Method getColor() gets / returns current color
Note:- In this lecture, we’ll focus on paint() method. 11
setting. 12
Cont… Cont…
import [Link].*; Example-2: Using JColorChooser
 Component JColorChooser import [Link].*;
import [Link].*;
• The JColorChooser class is used public class ColorChooserExample
to create a color chooser dialog extends JFrame implements ActionListener {
JFrame f;
box so that user can select any JButton b;
color. It inherits JComponent class. JTextArea ta;
ColorChooserExample(){
f=new JFrame("Color Chooser Example.");
• Method showDialog(Component cmp, String title, Color initColor) b=new JButton("Pad Color");
[Link](200,250,100,30);
- First argument: reference to parent Component (window ta=new JTextArea();
[Link](10,10,300,200);
from which dialog being displayed) [Link](this);
[Link](b);[Link](ta);
Modal dialog - user cannot interact with other dialogs while active. [Link](null);
- Second argument: String for title bar. [Link](400,400);
[Link](true);
- Third argument: Initial selected color. }
[Link](EXIT_ON_CLOSE);

• showDialog() returns a Color object public void actionPerformed(ActionEvent e){


Color c=[Link](this,"Choose",[Link]);
 Class Container [Link](c);
}
Method setBackground() - takes Color object
public static void main(String[] args) {
- Sets background color. 13 new ColorChooserExample(); 14
}
}
Cont… Cont…
Example-3: Using colors Outline: // set new drawing color using static Color objects Outline:
import [Link].*; [Link]( [Link] );
import [Link].*; import [Link]( 25, 75, 100, 20 ); define paint()
import [Link].*; [Link]( "Current RGB: " + [Link](), 130, 90 );

public class ShowColors extends JFrame { // display individual RGB values


public ShowColors() { Color c = [Link];
super( "Using colors" );
Class definition [Link]( c );
setSize( 400, 130 ); [Link]( 25, 100, 100, 20 );
setVisible(true); // show(); [Link]( "RGB values: " + [Link]() + ", " +
} [Link]() + ", " + [Link](), 130, 115 );
}
public void paint( Graphics g ) {
// set new drawing color using integers public static void main( String args[ ] ) {
ShowColors app = new ShowColors();
main() method
[Link]( new Color( 255, 0, 0 ) );
[Link]( 25, 25, 100, 20 );
[Link]( "Current RGB: " + [Link](), 130, 40 );
define paint() }
}
// set new drawing color using floats Program Output
[Link]( new Color( 0.0f, 1.0f, 0.0f ) );
[Link]( 25, 50, 100, 20 );
[Link]( "Current RGB: " + [Link](), 130, 65 );

15 16
Font Control Cont…
• Methods
• Class Font • isPlain()
• getStyle()
 The Font class states fonts, which are used to render text in a • Returns the style of this Font. • Indicates whether or not this Font object's
visible way. style is PLAIN.
• getSize()
 Constructor: creates a new Font from the specified font, and it • isBold()
• Returns the point size of this Font.
takes three arguments: • Indicates whether or not this Font object's
public Font( String name, int style, int size) • getName() style is BOLD.
• name: any font supported by system (Serif, Monospaced) • Returns the logical name of this Font.
• isItalic()
• style: constants [Link], [Link], [Link] • getFamily() • Indicates whether or not this Font object's
– Combinations: [Link] + [Link] • Returns the family name of this Font. style is ITALIC.
• size: measured in points (1/72 of an inch) • setFont(Font f)
• getFont()
 Use similar to Color • Is used to set the graphics current font to
Returns a Font object from the system
 [Link](fontObject); properties list.
the specified font.

17 18
Cont… Cont…
Example-4: Using fonts Outline:
Outline: // set current font to SansSerif (Helvetica),
import [Link].*; // plain, 14pt and draw a string
import [Link].*; import [Link]( new Font( "SansSerif", [Link], 14 ) ); define paint()
import [Link].*; [Link]( "SansSerif 14 point plain.", 20, 90 );

public class Fonts extends JFrame { // set current font to Serif (times), bold/italic,
public Fonts() { // 18pt and draw a string
super( "Using fonts" ); [Link]( [Link] );
setSize( 420, 125 );
Class definition [Link](new Font( "Serif", [Link] + [Link], 18 ) );
setVisible(true); // show(); [Link]( [Link]().getName() + " " +
} [Link]().getSize() + " point bold italic.", 20, 110 );
}
public void paint( Graphics g ) {
// set current font to Serif (Times), bold, 12pt public static void main( String args[] ) {
Fonts app = new Fonts();
main() method
// and draw a string
}
[Link]( new Font( "Serif", [Link], 12 ) );
[Link]( "Serif 12 point bold.", 20, 50 );
define paint() }

// set current font to Monospaced (Courier), Program Output


// italic, 24pt and draw a string
[Link]( new Font( "Monospaced", [Link], 24 ) );
[Link]( "Monospaced 24 point italic.", 20, 70 );
19 20
Cont… Cont…
• Class FontMetrics • FontMetrics (and Graphics) methods
• Has methods for getting font metrics: • getAscent()
• Determines the font ascent of the Font described by this FontMetrics object.
• [Link]() • getDescent()
• Determines the font descent of the Font described by this FontMetrics object
- returns FontMetrics object
• getLeading()
• Determines the standard leading of the Font described by this FontMetrics object.
leading
• getHeight()
height

Xy1 ascent

baseline
descent
• Gets the standard height of a line of text in this font.
• getFontMetrics()
• Gets the font metrics of the current font.

• getFontMetrics(Font f)

• ascent is the distance this string extends above the baseline. • Gets the font metrics for the specified font.
• descent is the distance this string descends below the baseline. 21 22
Cont… Cont…
Example-5: Using FontMetrics Outline: Font font = new Font( "Serif", [Link], 14 ); Outline:
fm = [Link]( font );
import [Link].*;
import
[Link]( font ); define paint()
import [Link].*; [Link]( "Current font: " + font, 10, 130 );
import [Link].*; [Link]( "Ascent: " + [Link](), 10, 145 );
[Link]( "Descent: " + [Link](), 10, 160 );
public class Metrics extends JFrame { [Link]( "Height: " + [Link](), 10, 175 );
public Metrics() { [Link]( "Leading: " + [Link](), 10, 190 );
super( "Demonstrating FontMetrics" ); Class definition }
setSize( 510, 210 );
setVisible(true); // show(); public static void main( String args[] ) {
} Metrics app = new Metrics(); main() method
}
public void paint( Graphics g ) { }
[Link]( new Font( "SansSerif", [Link], 12 ) );
FontMetrics fm = [Link]();
[Link]( "Current font: " + [Link](), 10, 40 ); define paint()
[Link]( "Ascent: " + [Link](), 10, 55 );
[Link]( "Descent: " + [Link](), 10, 70 ); Program Output
[Link]( "Height: " + [Link](), 10, 85 );
[Link]( "Leading: " + [Link](), 10, 100 );

23 24
Note: Program Output may differ on different computers
Drawing Lines, Rectangles and Ovals Cont…
• Graphics methods for drawing shapes: • Graphics methods for drawing shapes (Cont.)
• drawLine(x1, y1, x2, y2)  fill3DRect(x, y, width, height, raised)
• Draws a Line from (x1, y1) to (x2, y2). • Paints a 3-D highlighted rectangle filled with the current color.
• drawRect(x1, y1, width, height)  drawRoundRect(x, y, width, height, arcWidth, arcHeight)
• Draws a rectangle with upper left corner (x1,y1).
• Draws rectangle with rounded corners. See diagram next slide.
• fillRect(x1, y1, width, height)
 fillRoundRect(x, y, width, height, arcWidth, arcHeight)
• As above, except fills rectangle with current color.
• Fills the specified rounded corner rectangle with the current color.
• clearRect(x1, y1, width, height)  drawOval(x, y, width, height)
• As above, except fills rectangle with background color • Draws oval in bounding rectangle (see diagram).
• draw3DRect(x1, y1, width, height, isRaised) • Touches rectangle at midpoint of each side.
• Draws 3D rectangle, raised if isRaised is true, else lowered.
 fillOval(x, y, width, height)
• Fills an oval bounded by the specified rectangle with the current color.

25 26
Cont… Cont…
Example-6: Drawing Lines, Rectangles and Ovals Outline:
(x, y) import [Link].*;
drawRoundRect() parameters import [Link].*; import
import [Link].*;
arc height
public class LinesRectsOvals extends JFrame {
arc width
private String s = "Using drawString!";
height Class definition
public LinesRectsOvals() {
super( "Drawing lines, rectangles and ovals" );
setSize( 400, 165 );
setVisible(true); // show();
}
width define paint()
(x, y) public void paint( Graphics g ) {
[Link]( [Link] );
[Link]( 5, 35, 350, 35 );
drawOval() parameters
[Link]( [Link] );
height [Link]( 5, 40, 90, 55 );
[Link]( 100, 40, 90, 55 );
[Link]( [Link] );
[Link]( 195, 40, 90, 55, 50, 50 );
[Link]( 290, 40, 90, 55, 20, 20 );
width 27 28
Cont… Drawing Arcs
•Arc
[Link]( [Link] );
Outline:
g.draw3DRect( 5, 100, 90, 55, true );
g.fill3DRect( 100, 100, 90, 55, false ); define paint() • Portion of an oval.
[Link]( [Link] ); • Measured in degrees.
[Link]( 195, 100, 90, 55 );
[Link]( 290, 100, 90, 55 ); • Starts at a starting angle and sweeps the number of degrees
} specified by arc angle.
public static void main( String args[] ) {
main() method • Positive – counterclockwise.
}
LinesRectsOvals app = new LinesRectsOvals(); • Negative – clockwise.
}
• When drawing an arc, specify bounding rectangle for
an oval.
Program Output • drawArc(x, y, width, height, startAngle, arcAngle)
- is used to draw a circular or elliptical arc.
• fillArc(x, y, width, height, startAngle, arcAngle)
- as above but draws a solid arc (sector).
29 30
Cont… Cont…
Example-7: Drawing Arcs Outline: // start at 0 and sweep -270 degrees
import [Link].*; [Link]( [Link] );
Outline:
import [Link].*; [Link]( 185, 35, 80, 80 );
import
import [Link].*; [Link]( [Link] ); define paint()
[Link]( 185, 35, 80, 80, 0, -270 );
public class DrawArcs extends JFrame { // start at 0 and sweep 360 degrees
public DrawArcs() { [Link]( 15, 120, 80, 40, 0, 360 );
super( "Drawing Arcs" ); Class definition // start at 270 and sweep -90 degrees
setSize( 300, 170 ); [Link]( 100, 120, 80, 40, 270, -90 );
setVisible(true); // show(); // start at 0 and sweep -270 degrees
} [Link]( 185, 120, 80, 40, 0, -270 );
}
public void paint( Graphics g ) {
// start at 0 and sweep 360 degrees public static void main( String args[] ) {
[Link]( [Link] );
define paint() DrawArcs app = new DrawArcs(); main() method
[Link]( 15, 35, 80, 80 ); }
[Link]( [Link] ); }
[Link]( 15, 35, 80, 80, 0, 360 );
// start at 0 and sweep 110 degrees
[Link]( [Link] ); Program Output
[Link]( 100, 35, 80, 80 );
[Link]( [Link] );
[Link]( 100, 35, 80, 80, 0, 110 );
31 32
Drawing Polygons and Polylines Cont…
• Polygon - multisided shape. • Methods of class Polygon (Cont.):
• drawPolygon(myPolygon)
• Polyline - series of connected points.
• Draws specified closed polygon.
• Methods of class Polygon: • fillPolygon(xPoints[], yPoints[], points)
• drawPolygon(xPoints[], yPoints[], points)
• Draws a polygon, with x and y points specified in arrays. Last
• Draws a solid polygon.
argument specifies number of points. • fillPolygon(myPolygon)
• Closed polygon, even if last point different from first.
• Draws specified solid polygon.
• drawPolyline(xPoints[], yPoints[], points)
• Polygon(xValues[], yValues[], numberOfPoints)
• As above but draws a polyline.
• Open polyline. • Constructs a new polygon object.
• [Link](x, y)
• Add pairs of x-y coordinates to polygon object.
33 34
Cont… Cont…
Example-8: Drawing Polygons and Polylines Outline: Outline:
Polygon poly2 = new Polygon();
import [Link].*; [Link]( 165, 135 );
Import [Link]( 175, 150 );
define paint()
import [Link].*;
import [Link].*; [Link]( 270, 200 );
[Link]( 200, 220 );
public class DrawPolygons extends JFrame { Class definition [Link]( 130, 180 );
public DrawPolygons() {
super( "Drawing Polygons" ); [Link]( poly2 );
setSize( 275, 230 ); }
setVisible(true); // show();
} public static void main( String args[] ) { main() method
DrawPolygons app = new DrawPolygons();
public void paint( Graphics g ) { }
int xValues[ ] = { 20, 40, 50, 30, 20, 15 }; define paint() }
int yValues[ ] = { 50, 50, 60, 80, 80, 60 };
Polygon poly1 = new Polygon( xValues, yValues, 6 ); Program Output
[Link]( poly1 );
int xValues2[ ] = { 70, 90, 100, 80, 70, 65, 60 };
int yValues2[ ] = { 100, 100, 110, 110, 130, 110, 90 };
[Link]( xValues2, yValues2, 7 );
int xValues3[ ] = { 120, 140, 150, 190 };
int yValues3[ ] = { 40, 70, 80, 60 };
[Link]( xValues3, yValues3, 4 );
35 36

You might also like