-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCanvas.java
More file actions
483 lines (419 loc) · 14.3 KB
/
Copy pathCanvas.java
File metadata and controls
483 lines (419 loc) · 14.3 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Image;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.Timer;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.concurrent.TimeUnit;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFileChooser;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
/**
* Canvas is a class to allow for simple graphical drawing on a canvas. This is
* a modification of the general purpose Canvas, specially made for the BlueJ
* "shapes" example.
*
* @author: Bruce Quig Michael Kölling Brian Dahlem
* @version 2023.6.9
*/
public class Canvas {
// Note: The implementation of this class (specifically the handling of
// shape identity and colors) is slightly more complex than necessary. This
// is done on purpose to keep the interface and instance fields of the
// shape objects in this project clean and simple for educational purposes.
private static Canvas canvasSingleton;
/**
* Factory method to get the canvas singleton object.
*
* @return a reference to the applications canvas
*/
public static Canvas getCanvas() {
if (canvasSingleton == null) {
canvasSingleton = new Canvas("Picture Demo", 800, 600, Color.white);
}
canvasSingleton.setVisible(true);
return canvasSingleton;
}
// ----- instance part -----
private int width;
private int height;
private JFrame frame;
private CanvasPane canvas;
private BufferStrategy bs;
private Color backgroundColor;
private Image canvasImage;
private final Map<Object, DrawShape> shapes;
private String title;
private boolean paused = false;
private boolean firstShown = false;
private boolean drawing = false;
private JDialog recWindow;
private long recFrames = 0;
private JLabel timeLabel;
private JPopupMenu popMenu;
private JMenuItem savePic;
private JMenuItem saveVid;
private static final int FPS = 30;
/**
* Create a Canvas.
*
* @param title title to appear in Canvas Frame
* @param width the desired width for the canvas
* @param height the desired height for the canvas
* @param bgColor the desired background color of the canvas
*/
private Canvas(String title, int width, int height, Color bgColor) {
this.title = title;
this.width = width;
this.height = height;
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas = new CanvasPane();
frame.add(canvas);
frame.setTitle(title);
frame.setLocation(30, 30);
canvas.setPreferredSize(new Dimension(width, height));
backgroundColor = bgColor;
frame.pack();
shapes = new LinkedHashMap<>(1000);
// Add a context menu to allow saving the canvas
popMenu = new JPopupMenu() {
{
savePic = new JMenuItem("Save as png...");
savePic.addActionListener(e->savePic());
add(savePic);
}
};
// Add a mouse listener that will pop up the context menu
canvas.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
doPop(e);
}
public void mouseReleased(MouseEvent e) {
doPop(e);
}
private void doPop(MouseEvent e) {
if (!e.isPopupTrigger()) {
return;
}
popMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
}
/**
* Set the canvas visibility and brings canvas to the front of screen when
* made visible. This method can also be used to bring an already visible
* canvas to the front of other windows.
*
* @param visible boolean value representing the desired visibility of the
* canvas (true or false)
*/
public void setVisible(boolean visible) {
if (!firstShown && visible) {
firstShown = true;
// first time: instantiate the image and fill it with
// the background color
Dimension size = canvas.getSize();
canvas.createBufferStrategy(2);
bs = canvas.getBufferStrategy();
Graphics graphic = bs.getDrawGraphics();
graphic.setColor(backgroundColor);
graphic.fillRect(0, 0, size.width, size.height);
graphic.setColor(Color.black);
graphic.dispose();
bs.show();
}
frame.setVisible(visible);
}
/**
* Determine the width of the canvas
*/
public int getWidth() {
return canvas.getWidth();
}
/**
* Determine the height of the canvas
*/
public int getHeight() {
return canvas.getHeight();
}
/**
* Pause automatic redraws
*/
public void pause(boolean pause) {
this.paused = pause;
}
/**
* Are automatic redraws paused
*/
public boolean isPaused() {
return this.paused;
}
/**
* Draw a given shape onto the canvas.
*
* @param referenceObject an object to define identity for this shape
* @param shapeFunction a function that draws the shape on a graphics
* context
*/
public void add(Object referenceObject, DrawShape shapeFunction) {
synchronized (shapes) {
if (shapes.containsKey(referenceObject)) {
throw new IllegalArgumentException("Shape already added to canvas");
}
shapes.put(referenceObject, shapeFunction);
}
if (!paused) {
redraw();
}
}
/**
* Erase a given shape from the screen.
*
* @param referenceObject the shape object to be erased
*/
public void remove(Object referenceObject) {
synchronized (shapes) {
if (!shapes.containsKey(referenceObject)) {
throw new IllegalArgumentException("Shape not added to canvas");
}
shapes.remove(referenceObject);
}
if (!paused) {
redraw();
}
}
/**
* Change the name of this canvas
*
* @param title the new name for the canvas
*/
public void setTitle(String title) {
this.title = title;
frame.setTitle(title);
}
/**
* Set the canvas's background color
*
* @param bgColor the new background color for the canvas.
*/
public void setBackgroundColor(Color bgColor) {
this.backgroundColor = bgColor;
}
/**
* Set the canvas's background color
*
* @param bgColor the new background color for the canvas.
*/
public void setBackgroundColor(String bgColor) {
setBackgroundColor(getColor(bgColor));
}
/**
* Wait for a specified number of milliseconds before finishing. This
* provides an easy way to specify a small delay which can be used when
* producing animations.
*
* @param milliseconds the number
*/
public void wait(int milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
// ignoring exceptions at the moment
}
}
/**
* Redraw all shapes currently on the Canvas.
*/
public void redraw() {
// Draw the shapes on the next buffer's graphics context
if (bs != null) {
Graphics gc = bs.getDrawGraphics();
redraw(gc);
gc.dispose();
// Show the buffer
bs.show();
}
}
/**
* Redraw all shapes onto a graphics context
*/
private void redraw(Graphics gc) {
synchronized (shapes) {
// Draw the background
gc.setColor(backgroundColor);
Dimension size = canvas.getSize();
gc.fillRect(0, 0, size.width, size.height);
// Draw all of the shapes
shapes.forEach((k, shape) -> shape.draw(gc));
}
}
/**
* Erase the whole canvas. (Does not repaint.)
*/
private void erase() {
Graphics buffer = bs.getDrawGraphics();
buffer.setColor(backgroundColor);
Dimension size = canvas.getSize();
buffer.fillRect(0, 0, size.width, size.height);
buffer.dispose();
bs.show();
}
/**
* Transform a color string into a usable color
*
* @param colorString the new color for the foreground of the Canvas
*/
public static Color getColor(String colorString) {
Color c;
if (colorString.equals("red")) {
c = new Color(235, 25, 25);
} else if (colorString.equals("black")) {
c = Color.black;
} else if (colorString.equals("blue")) {
c = new Color(30, 75, 220);
} else if (colorString.equals("cyan")) {
c = new Color(30, 229, 220);
} else if (colorString.equals("brown")) {
c = new Color(110, 80, 0);
} else if (colorString.equals("yellow")) {
c = new Color(255, 230, 0);
} else if (colorString.equals("green")) {
c = new Color(80, 160, 60);
} else if (colorString.equals("magenta")) {
c = Color.magenta;
} else if (colorString.equals("white")) {
c = Color.white;
} else if (colorString.startsWith("#") && colorString.length() == 7) {
int red = Integer.parseInt(colorString.substring(1, 3), 16);
int green = Integer.parseInt(colorString.substring(3, 5), 16);
int blue = Integer.parseInt(colorString.substring(5, 7), 16);
c = new Color(red, green, blue);
} else {
c = Color.black;
}
return c;
}
/**
* **********************************************************************
* Inner class CanvasPane - the actual canvas component contained in the
* Canvas frame.
*/
private class CanvasPane extends java.awt.Canvas {
@Override
public void paint(Graphics g) {
redraw();
}
}
/**
* ***********************************************************************
* Inner interface DrawShape - a functional interface that allows a shape to
* provide the canvas with a method to draw the shape
*/
public interface DrawShape {
public void draw(Graphics g);
}
private void savePic() {
File file = newFile("png", "PNG Images");
if (file == null) {
return;
}
// If that file exists, confirm overwrite.
if (file.exists()) {
int overwrite = JOptionPane.showConfirmDialog(frame,
"A file named " + file + " exists.\nOverwrite?", "File Exists",
JOptionPane.YES_NO_OPTION);
if (overwrite == JOptionPane.NO_OPTION) {
return;
}
}
Font font = new Font("SansSerif", Font.PLAIN, 20);
try {
InputStream fnt_stream = getClass().getResourceAsStream("Caveat.ttf");
Font myFont = Font.createFont(Font.TRUETYPE_FONT, fnt_stream);
font = myFont.deriveFont(Font.BOLD, 20f);
} catch (FontFormatException | IOException ign) {
// Ignore font exceptions and go with default font
}
FontMetrics fm = canvas.getFontMetrics(font);
int fontheight = fm.getHeight();
// Create a buffered image from the picture
BufferedImage buffer = new BufferedImage(width, height + fontheight + 2,
BufferedImage.TYPE_INT_RGB);
Graphics bgc = buffer.createGraphics();
bgc.setColor(Color.white);
bgc.fillRect(0, 0, width, height + fontheight + 2);
redraw(bgc);
bgc.setColor(Color.black);
bgc.setFont(font);
bgc.drawString(frame.getTitle(), 0, height + fm.getAscent() + 1);
// Save the image
try {
ImageIO.write(buffer, "png", file);
// Inform the user of success in saving.
JOptionPane.showMessageDialog(frame,
"Image saved to: " + file, "File Saved",
JOptionPane.INFORMATION_MESSAGE);
} catch (java.io.IOException exc) {
// Alert the user if there is an error.
JOptionPane.showMessageDialog(frame,
"Could not save image to: " + file, "File Error",
JOptionPane.ERROR_MESSAGE);
}
}
private File newFile(String fileExtention, String fileTypeDescription) {
// Ask the user for a filename to save to.
JFileChooser fc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
fileTypeDescription, fileExtention);
fc.setFileFilter(filter);
int returnVal = fc.showSaveDialog(frame);
// Cancel if the user pressed "Cancel"...
if (returnVal == JFileChooser.CANCEL_OPTION) {
return null;
}
// Get the name of the file the user entered
File file = fc.getSelectedFile();
String fname = file.getAbsolutePath();
if (!fname.endsWith("." + fileExtention)) {
fname = fname + "." + fileExtention;
}
file = new File(fname);
// If that file exists, confirm overwrite.
if (file.exists()) {
int overwrite = JOptionPane.showConfirmDialog(frame,
"A file named " + file + " exists.\nOverwrite?", "File Exists",
JOptionPane.YES_NO_OPTION);
if (overwrite == JOptionPane.NO_OPTION) {
return null;
}
}
return file;
}
public static void makePic() {
Canvas c = Canvas.getCanvas();
c.savePic();
c.frame.dispose();
}
}