|
Basics of Computer Graphics
in Java |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
The (Linear) Color Cube
Graphics2D ObjectShape Interface
setFont method in
Graphics2D
Line Metrics
The x and y passed to
drawString(String s, float x, float y) are the left end
of the baseline.
public void paint(Graphics g)
methodJComponent which does very little in its
paint() methodimport java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
/**
* A simple example of graphics
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class Example extends JComponent
{
public static final float[] DASHED_PATTERN = {10.0f, 10.0f};
public static final float[] DOTTED_PATTERN = { 2.0f, 2.0f};
/**
* Render this JComponent
*
* @param g The rendering engine to use
*/
public void paint(Graphics g)
{
Font serifFont;
GradientPaint gradient;
Graphics2D g2;
Line2D.Float line;
Path2D.Float path;
Rectangle2D.Float rectangle;
Stroke dashed, dotted, solid;
g2 = (Graphics2D)g;
// Create some Stroke objects
dashed = new BasicStroke(2.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f,
DASHED_PATTERN,
0.0f);
dotted = new BasicStroke(2.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f,
DOTTED_PATTERN,
0.0f);
solid = new BasicStroke(2.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER);
// Create a Font object
serifFont = new Font(Font.SERIF, Font.PLAIN, 20);
// Create and render some lines
g2.setColor(Color.red);
line = new Line2D.Float(0f,0f,100f,100f);
g2.draw(line);
line = new Line2D.Float(100f,100f,200f,200f);
g2.setStroke(dashed);
g2.draw(line);
line = new Line2D.Float(200f,200f,300f,300f);
g2.setStroke(dotted);
g2.draw(line);
// Render some text
g2.setColor(Color.blue);
g2.setFont(serifFont);
g2.drawString("Hello World",40.0f,100.0f);
// Create a Paint object
gradient = new GradientPaint(300.0f,300.0f,Color.green,
500.0f,300.0f,Color.yellow);
// Create and render a rectangle
rectangle = new Rectangle2D.Float(300f,300f,200f,100f);
g2.setPaint(gradient);
g2.fill(rectangle);
g2.setStroke(solid);
g2.setColor(Color.black);
g2.draw(rectangle);
// Create and render a Path2D
path = new Path2D.Float();
path.moveTo(100.0f,300.0f);
path.lineTo(200.0f,400.0f);
path.lineTo(100.0f,350.0f);
path.lineTo( 0.0f,400.0f);
path.lineTo(100.0f,300.0f);
g2.draw(path);
}
}
import java.awt.*;
import javax.swing.*;
/**
* A simple example of graphics
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class ExampleDriver
{
/**
* The entry point
*
* @param args The command line arguments
*/
public static void main(String[] args)
{
Container contentPane;
Example example;
JFrame window;
window = new JFrame("Graphics Example");
contentPane = window.getContentPane();
contentPane.setLayout(null);
example = new Example();
example.setBounds(0,0,500,500);
window.add(example);
window.setSize(600,600);
window.setVisible(true);
}
}