Continued…

Download Report

Transcript Continued…

Chapter 5
Programming Graphics
Chapter Goals
• To be able to write applications with simple
graphical user interfaces
• To display graphical shapes such as lines and
ellipses
• To use colors
• To display drawings consisting of many
shapes
• To read input from a dialog box
• To develop test cases that validate the
correctness of your programs
Agenda
• Basic user interface elements
 JFrame
 JPanel
 Graphical shapes, lines etc.
• RectangleDemo revisited
 ActionListener
 JButton
 LayoutManager
• Function Plotter
Frame Windows
•
The JFrame class
JFrame frame = new JFrame();
frame.setSize(300, 400);
frame.setTitle("An Empty Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
•
import javax.swing.*;
A Frame Window
Figure 1:
A Frame Window
File EmptyFrameViewer.java
01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
17:
18:
import javax.swing.*;
public class EmptyFrameViewer
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("An Empty Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Drawing Shapes
• paintComponent: called whenever the
component needs to be repainted:
public class RectangleComponent extends JComponent
{
public void paintComponent(Graphics g)
{
// Recover Graphics2D
Graphics2D g2 = (Graphics2D) g;
. . .
}
}
• If you use a JPanel instead of a
JComponent, the method is called paint
Drawing Shapes
• Graphics class lets you manipulate the
graphics state (such as current color)
• Graphics2D class has methods to draw
shape objects
• Use a cast to recover the Graphics2D object
from the Graphics parameter
Rectangle box = new Rectangle(5, 10, 20, 30);
g2.draw(box);
• java.awt package
RectangleDemoII

RectangleDemoII extends (is a) JPanel and can
therefore be drawn upon
public class RectangleDemoII extends JPanel { ...

Out of main()!
public static void main(String[] args) {
RectangleDemoII me = new RectangleDemoII();
}




Construct Rectangle objects
Allow the user to specify one Rectangle
Construct a JFrame
Set this “Jpanel” as the JFrame's contentPane
frame.setContentPane(this);

Make the frame visible
Drawing Rectangles
rect1, rect2,...
draw()
Graphics2D
JPanel
JFrame
Figure 2:
Drawing Rectangles
Graphical Shapes
• Rectangle, Ellipse2D.Double, and
Line2D.Double describe graphical shapes
• We must construct objects and then have a
Graphics object draw the shape
import java.awt.geom.Ellipse2D; // no .Double
Ellipse2D.Double ellipse = new Ellipse2D.Double(
x, y, width, height);
g2.draw(ellipse);
An Ellipse
Figure 6:
An Ellipse and Its Bounding Box
Drawing Lines
• To draw a line:
Line2D.Double segment = new Line2D.Double(x1, y1, x2, y2);
or,
Point2D.Double from = new Point2D.Double(x1, y1);
Point2D.Double to = new Point2D.Double(x2, y2);
Line2D.Double segment = new Line2D.Double(from, to);
Drawing Strings
g2.drawString("Message", 50, 100);
Figure 7:
Basepoint and Baseline
Colors
• Standard colors Color.BLUE, Color.RED,
Color.PINK etc.
• Specify red, green, blue between 0.0F and
1.0F Color magenta = new Color(1.0F,
0.0F, 1.0F); // F = float
• Set color in graphics context
g2.setColor(magenta);
• Color is used when drawing and filling shapes
g2.fill(rectangle); // filled with current color
Drawing Complex Shapes
• Good practice: Make a class for each
graphical shape
class Car
{
. . .
public void draw(Graphics2D g2)
{
// Drawing instructions
. . .
}
}
• Plan complex shapes by making sketches on
graph paper
Drawing Graphical Shapes
Rectangle leftRectangle = new Rectangle(100, 100, 30, 60);
Rectangle rightRectangle = new Rectangle(160, 100, 30, 60);
Line2D.Double topLine
= new Line2D.Double(130, 100, 160, 100);
Line2D.Double bottomLine
= new Line2D.Double(130, 160, 160, 160);
Reading numerical input
• NumericalInput allows easy input of up to
five numerical (double) values
int x, y, w, h;
// x, y-coordinates, width and height
NumericalInput ni = new NumericalInput(
"x", "y", "width", "height");
while(!ni.isReady());// Wait for input
x = (int) ni.getFirstInput(); // Obtain input
y = (int) ni.getSecondInput();
w = (int) ni.getThirdInput();
h = (int) ni.getFourthInput();
rect3 = new Rectangle(x,y,w,h);
Reading numerical input
Upon receiving an
event, the N.I.
acquires all input
values
Click!
Figure 13:
An Input Dialog Box
Registered as
ActionListener
NumericalInput
PlotDemo
• Plots a parabola corresponding to a 2nd order
polynomial p(x) = a x^2 + b x + c
• PlotDemo: Class representing a 2nd order
polynomial
• PlotDemo: Main application – obtains user
input via a NumericalInput object and starts
the plotting
• FunctionPlotter: JFrame containing a
PolynomialGraph as its contentPane, as well
Continued…
as an Exit-button
PlotDemo
• PolynomialGraph: JPanel handling all plotting
in its paintComponent method:
 It first draws a coordinate system
 Then it uses a for loop to step through all x-coordinates
and computes the corresponding y-values by invoking
appropriate methods in the Polynomial object
 Then it draws a line segment between the previous
point and the current point
Continued…
Classes (Objects) in PlotDemo
paint()
PolynomialGraph
(JPanel)
FunctionPlotter
(JFrame)
JButton
p(x)
coefficients
Polynomial
Click!
NumericalInput
Summary
• Graphical user interfaces are important, but
sometimes require a lot of work
• To draw custom shapes, you put the drawing
code in the paint method in a Jpanel
• Other components, such as JButton, handle
drawing by themselves
• Components must be added to a container
• If you want to be able to receive events, you
must register ActionListeners with the event
sources
Comparing Visual and Numerical
Information
• Compute intersection between circle and
vertical line
• Circle has radius r = 100 and center (a, b) =
(100, 100)
• Line has constant x value
Note: This and the following pages
are not part of the lecture; it is purely
included for reference purposes
Continued…
Comparing Visual and Numerical
Information
• Calculate intersection points using mathematics:
Equation of a circle with radius r and center point
(a, b) is
If you know x, then you can solve for y:
Comparing Visual and Numerical
Information
• That is easy to compute in Java:
double root = Math.sqrt(r * r - (x - a) * (x - a));
double y1 = b + root;
double y2 = b - root;
• Plot circle, line, computed intersection points
• Visual and numerical results should be the
same
Intersection of a Line and a Circle
Figure 15
Intersection of a Line and a Circle
File
IntersectionComponent.java
01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
import
import
import
import
import
java.awt.Graphics;
java.awt.Graphics2D;
java.awt.geom.Ellipse2D;
java.awt.geom.Line2D;
javax.swing.JComponent;
/**
A component that computes and draws the intersection points
of a circle and a line.
*/
public class IntersectionComponent extends JComponent
{
/**
Constructs the component from a given x-value for the line
@param anX the x-value for the line (between 0 and 200)
*/
Continued…
File
IntersectionComponent.java
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
public IntersectionComponent(double anX)
{
x = anX;
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
// Draw the circle
final double RADIUS = 100;
Ellipse2D.Double circle
= new Ellipse2D.Double(0, 0, 2 * RADIUS, 2 * RADIUS);
g2.draw(circle);
// Draw the vertical line
Continued…
File
IntersectionComponent.java
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
Line2D.Double line
= new Line2D.Double(x, 0, x, 2 * RADIUS);
g2.draw(line);
// Compute the intersection points
double a = RADIUS;
double b = RADIUS;
double root = Math.sqrt(RADIUS * RADIUS - (x double y1 = b + root;
double y2 = b - root;
* (x - a));
// Draw the intersection points
LabeledPoint p1 = new LabeledPoint(x, y1);
LabeledPoint p2 = new LabeledPoint(x, y2);
Continued…
File
IntersectionComponent.java
53:
54:
55:
56:
57:
58:
59: }
p1.draw(g2);
p2.draw(g2);
}
private double x;
File IntersectionViewer.java
01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class IntersectionViewer
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Continued…
File IntersectionViewer.java
16:
17:
18:
19:
20:
21:
22:
23:
24: }
String input = JOptionPane.showInputDialog("Enter x");
double x = Double.parseDouble(input);
IntersectionComponent component
= new IntersectionComponent(x);
frame.add(component);
frame.setVisible(true);
}
File LabeledPoint.java
01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
17:
18:
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
/**
A point with a label showing the point's coordinates.
*/
public class LabeledPoint
{
/**
Construct a labeled point.
@param anX the x coordinate
@param aY the y coordinate
*/
public LabeledPoint(double anX, double aY)
{
x = anX;
y = aY;
}
Continued…
File LabeledPoint.java
19:
20:
21:
22:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
/**
Draws the point as a small circle with a coordinate label.
@param g2 the graphics context23:
*/
public void draw(Graphics2D g2)
{
// Draw a small circle centered around (x, y)
Ellipse2D.Double circle = new Ellipse2D.Double(
x - SMALL_CIRCLE_RADIUS,
y - SMALL_CIRCLE_RADIUS,
2 * SMALL_CIRCLE_RADIUS,
2 * SMALL_CIRCLE_RADIUS);
g2.draw(circle);
// Draw the label
Continued…