-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDrawTest.java
80 lines (64 loc) · 1.96 KB
/
DrawTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package draw;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
/**
* @author Cay Horstmann
* @version 1.33 2007-05-12
*/
public class DrawTest {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new DrawFrame();
frame.setTitle("DrawTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
/**
* A frame that contains a pane with drawings
*/
class DrawFrame extends JFrame {
public DrawFrame() {
add(new DrawComponent());
pack();
}
}
/**
* A component that displays rectangles and ellipses.
*/
class DrawComponent extends JComponent {
private static final int DEFAULT_WIDTH = 400;
private static final int DEFAULT_HEIGHT = 400;
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// draw a rectangle
double leftX = 100;
double topY = 100;
double width = 200;
double height = 150;
Rectangle2D rectangle2D = new Rectangle2D.Double(leftX, topY, width, height);
g2.draw(rectangle2D);
// draw the enclosed ellipse
Ellipse2D ellipse2D = new Ellipse2D.Double();
ellipse2D.setFrame(rectangle2D);
g2.draw(ellipse2D);
// draw a diagonal line
g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height));
// draw a circle whit the same center
double centerX = rectangle2D.getX();
double centerY = rectangle2D.getY();
double radius = 150;
Ellipse2D circle = new Ellipse2D.Double();
circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius);
g2.draw(circle);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
}