- Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathShapePanel.java
More file actions
Latest commit
221 lines (201 loc) · 8.48 KB
/
Copy pathShapePanel.java
File metadata and controls
221 lines (201 loc) · 8.48 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
importjava.awt.BasicStroke;
importjava.awt.Color;
importjava.awt.Dimension;
importjava.awt.FlowLayout;
importjava.awt.Font;
importjava.awt.GradientPaint;
importjava.awt.Graphics;
importjava.awt.Graphics2D;
importjava.awt.RenderingHints;
importjava.awt.geom.AffineTransform;
importjava.awt.geom.Area;
importjava.awt.geom.Ellipse2D;
importjava.awt.geom.Path2D;
importjava.awt.geom.Rectangle2D;
importjava.awt.geom.RoundRectangle2D;
importjavax.swing.BorderFactory;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.SwingUtilities;
importjavax.swing.border.BevelBorder;
/**
* A custom Swing component that displays an assortment of geometric shapes
* rendered in various ways: solid fills, gradient paints, affine transforms,
* constructive solid geometry, and text rendering.
* <p>
* This example has no interaction (no listeners) — it focuses purely on the
* rendering pipeline of Java 2D. Two instances are shown side by side so
* you can compare anti-aliased vs. aliased rendering.
* <p>
* Updated for modern Java with better naming and Swing threading best practices.
*
* @author Ilkka Kokkarinen
*/
publicclassShapePanelextendsJPanel {
privatefinalbooleanantiAlias;
// -----------------------------------------------------------------------
// Construction
// -----------------------------------------------------------------------
/**
* Create a ShapePanel with the given anti-aliasing setting.
*
* @param antiAlias whether rendering should use anti-aliasing
*/
publicShapePanel(booleanantiAlias) {
this.antiAlias = antiAlias;
// The one setting you *must* provide for a custom Swing component.
setPreferredSize(newDimension(500, 300));
// Optional cosmetic settings.
setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
setToolTipText("Anti-aliasing is " + (antiAlias ? "on" : "off"));
}
// -----------------------------------------------------------------------
// Rendering — the heart of this example.
// -----------------------------------------------------------------------
/**
* Render the component's contents. Swing calls this method whenever the
* component needs to be redrawn (e.g. after a resize or when first shown).
*
* @param g the {@code Graphics} context provided by Swing
*/
@Override
protectedvoidpaintComponent(Graphicsg) {
super.paintComponent(g); // Erase previous contents.
// Downcast to Graphics2D for access to the modern Java 2D API.
varg2 = (Graphics2D) g;
if (antiAlias) {
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON
);
}
drawConcentricSquares(g2);
drawRoundedRectangle(g2);
drawTransformedEllipse(g2);
drawStar(g2);
drawText(g2);
}
// -----------------------------------------------------------------------
// Individual shape-drawing methods, factored out for clarity.
// -----------------------------------------------------------------------
/**
* Concentric squares: a simple loop demonstrating the polymorphic
* {@code draw} method that can render the outline of <em>any</em> Shape.
*/
privatevoiddrawConcentricSquares(Graphics2Dg2) {
g2.setStroke(newBasicStroke(3.0f));
g2.setPaint(Color.RED);
for (intsize = 0; size < 150; size += 10) {
doubleoffset = size / 2.0;
g2.draw(newRectangle2D.Double(100 - offset, 100 - offset, size, size));
}
}
/**
* A rounded rectangle filled with a gradient and outlined in orange.
* Demonstrates: GradientPaint, fill vs. draw, RoundRectangle2D.
*/
privatevoiddrawRoundedRectangle(Graphics2Dg2) {
varroundRect = newRoundRectangle2D.Double(200, 50, 100, 100, 30, 45);
g2.setStroke(newBasicStroke(8.0f));
g2.setPaint(newGradientPaint(210, 60, Color.YELLOW, 290, 140, Color.BLUE));
g2.fill(roundRect);
g2.setPaint(Color.ORANGE);
g2.draw(roundRect);
}
/**
* An ellipse that is rotated and then has a circular hole subtracted.
* Demonstrates: Area (constructive solid geometry), AffineTransform,
* and the fact that polymorphic draw/fill work on any Shape — including
* these computed composite areas.
*/
privatevoiddrawTransformedEllipse(Graphics2Dg2) {
// An ellipse defined by its invisible bounding rectangle.
varellipse = newArea(newEllipse2D.Double(350, 50, 70, 140));
// Rotate 13° around the center of the ellipse.
// Note: AffineTransform uses radians, not degrees.
varrotation = AffineTransform.getRotateInstance(
Math.toRadians(13), 385, 120
);
ellipse = ellipse.createTransformedArea(rotation);
// Constructive solid geometry: subtract a circular hole.
// Other available operations: add, intersect, exclusiveOr.
ellipse.subtract(newArea(newEllipse2D.Double(400, 100, 50, 50)));
// Fill with a gradient, then draw the outline.
g2.setPaint(newGradientPaint(370, 60, Color.BLACK, 360, 150, Color.WHITE));
g2.fill(ellipse);
g2.setStroke(newBasicStroke(
5.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND
));
g2.setPaint(Color.BLUE);
g2.draw(ellipse);
}
/**
* A ten-pointed star built as a polygon path, partially clipped by the
* component bounds. Demonstrates: Path2D for custom polygon shapes, and
* automatic clipping by the rendering engine.
*/
privatevoiddrawStar(Graphics2Dg2) {
finalintcenterX = 150;
finalintcenterY = 250;
finalintpoints = 10;
finaldoubleouterRadius = 100;
finaldoubleinnerRadius = 50;
intvertices = 2 * points; // A 10-point star has 20 polygon vertices.
varpath = newPath2D.Double();
for (inti = 0; i < vertices; i++) {
doubleangle = i * 2 * Math.PI / vertices;
doubleradius = (i % 2 == 0) ? outerRadius : innerRadius;
doublex = centerX + radius * Math.cos(angle);
doubley = centerY + radius * Math.sin(angle);
if (i == 0) {
path.moveTo(x, y); // First vertex starts the path.
} else {
path.lineTo(x, y); // Subsequent vertices add line segments.
}
}
path.closePath();
// Convert the closed path into an Area and render it.
varstarArea = newArea(path);
g2.setStroke(newBasicStroke(
5.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND
));
g2.setPaint(Color.WHITE);
g2.fill(starArea);
g2.setPaint(Color.BLACK);
g2.draw(starArea);
}
/**
* Render some text. Font glyphs are ultimately just curves and line
* segments — their rendering is fundamentally no different from the
* shapes above.
*/
privatevoiddrawText(Graphics2Dg2) {
g2.setColor(Color.BLACK);
// The Font constructor hooks into the fonts installed on your system.
g2.setFont(newFont("Serif", Font.ITALIC, 28));
// Note how the letter 'y' reaches below the baseline.
g2.drawString("Hello, wyrld!", 300, 250);
}
// -----------------------------------------------------------------------
// Main — create a JFrame with two ShapePanels for comparison.
// -----------------------------------------------------------------------
/**
* Launch the demo. A JPanel cannot exist alone on screen — it must be
* placed inside a top-level container, which here is a JFrame.
*/
publicstaticvoidmain(String[] args) {
// Swing components must be created and manipulated on the Event
// Dispatch Thread (EDT). SwingUtilities.invokeLater ensures this.
SwingUtilities.invokeLater(() -> {
varframe = newJFrame("ShapePanel Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// FlowLayout places the two panels side by side, unlike the
// default BorderLayout which would stack or stretch them.
frame.setLayout(newFlowLayout());
frame.add(newShapePanel(true)); // with anti-aliasing
frame.add(newShapePanel(false)); // without anti-aliasing
frame.pack();
frame.setVisible(true);
});
}
}