-
Notifications
You must be signed in to change notification settings - Fork 0
/
DrawingPanel.java
4773 lines (4259 loc) · 182 KB
/
DrawingPanel.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
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* =====================================================================
* DrawingPanel.java
* Simplified Java drawing window class
* to accompany Building Java Programs textbook and associated materials
*
* authors: Marty Stepp, Stanford University
* Stuart Reges, University of Washington
* version: 4.05, 2016/09/07 (BJP 5th edition)
* (make sure to also update version string in Javadoc header below!)
* =====================================================================
*
* COMPATIBILITY NOTE: This version of DrawingPanel requires Java 8 or higher.
* If you need a version that works on Java 7 or lower, please see our
* web site at http://www.buildingjavaprograms.com/ .
* To make this file work on Java 7 and lower, you must make two small
* modifications to its source code.
* Search for the two occurrences of the annotation @FunctionalInterface
* and comment them out or remove those lines.
* Then the file should compile and run properly on older versions of Java.
*
* =====================================================================
*
* The DrawingPanel class provides a simple interface for drawing persistent
* images using a Graphics object. An internal BufferedImage object is used
* to keep track of what has been drawn. A client of the class simply
* constructs a DrawingPanel of a particular size and then draws on it with
* the Graphics object, setting the background color if they so choose.
* See JavaDoc comments below for more information.
*/
import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.image.ImageObserver;
import java.text.AttributedCharacterIterator;
import java.util.Collections;
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.Exception;
import java.lang.Integer;
import java.lang.InterruptedException;
import java.lang.Math;
import java.lang.Object;
import java.lang.OutOfMemoryError;
import java.lang.SecurityException;
import java.lang.String;
import java.lang.System;
import java.lang.Thread;
import java.net.URL;
import java.net.NoRouteToHostException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.MouseInputListener;
import javax.swing.filechooser.FileFilter;
/**
*
* DrawingPanel is a simplified Java drawing window class to accompany
* Building Java Programs textbook and associated materials.
*
* <p>
* Authors: Marty Stepp (Stanford University) and Stuart Reges (University of Washington).
*
* <p>
* Version: 4.05, 2016/09/07 (to accompany BJP 5th edition).
*
* <p>
* You can always download the latest {@code DrawingPanel} from
* <a target="_blank" href="http://www.buildingjavaprograms.com/drawingpanel/DrawingPanel.java">
* http://www.buildingjavaprograms.com/drawingpanel/DrawingPanel.java</a> .
*
* <p>
* For more information and related materials, please visit
* <a target="_blank" href="http://www.buildingjavaprograms.com">
* www.buildingjavaprograms.com</a> .
*
* <p>
* COMPATIBILITY NOTE: This version of DrawingPanel requires Java 8 or higher.
* To make this file work on Java 7 and lower, you must make two small
* modifications to its source code.
* Search for the two occurrences of the annotation @FunctionalInterface
* and comment them out or remove those lines.
* Then the file should compile and run properly on older versions of Java.
*
* <h3>Description:</h3>
*
* <p>
* The {@code DrawingPanel} class provides a simple interface for drawing persistent
* images using a {@code Graphics} object. An internal {@code BufferedImage} object is used
* to keep track of what has been drawn. A client of the class simply
* constructs a {@code DrawingPanel} of a particular size and then draws on it with
* the {@code Graphics} object, setting the background color if they so choose.
* </p>
*
* <p>
* The intention is that this custom library will mostly "stay out of the way"
* so that the client mostly interacts with a standard Java {@code java.awt.Graphics}
* object, and therefore most of the experience gained while using this library
* will transfer to Java graphics programming in other contexts.
* {@code DrawingPanel} is not intended to be a full rich graphical library for things
* like object-oriented drawing of shapes, animations, creating games, etc.
* </p>
*
* <h3>Example basic usage:</h3>
*
* <p>
* Here is a canonical example of creating a {@code DrawingPanel} of a given size and
* using it to draw a few shapes.
* </p>
*
* <pre>
* // basic usage example
* DrawingPanel panel = new DrawingPanel(600, 400);
* Graphics g = panel.getGraphics();
* g.setColor(Color.RED);
* g.fillRect(17, 45, 139, 241);
* g.drawOval(234, 77, 100, 100);
* ...
* </pre>
*
* <p>
* To ensure that the image is always displayed, a timer calls repaint at
* regular intervals.
* </p>
*
* <h3>Pixel processing (new in BJP 4th edition):</h3>
*
* <p>
* This version of {@code DrawingPanel} allows you to loop over the pixels of an image.
* You can process each pixel as a {@code Color} object (easier OO interface, but takes
* more CPU and memory to run) or as a 32-bit RGB integer (clunkier to use, but
* much more efficient in runtime and memory usage).
* Look at the methods get/setPixel(s) to get a better idea.
*
* <pre>
* // example of horizontally flipping an image
* public static void flipHorizontal(DrawingPanel panel) {
* int width = panel.getWidth();
* int height = panel.getHeight();
* int[] pixels = panel.getPixelsRGB();
* for (int row = 0; row < height; row++) {
* for (int col = 0; col < width / 2; col++) {
* // swap this pixel with the one opposite it
* int col2 = width - 1 - col;
* int temp = pixels[row][col];
* pixels[row][col] = pixels[row][col2];
* pixels[row][col2] = temp;
* }
* }
* panel.setPixels(pixels);
* }
* </pre>
*
* <h3>Event listeners and lambdas (new in BJP 4th edition):</h3>
*
* <p>
* With Java 8, you can now attach event handlers to listen to keyboard and mouse
* events that occur in a {@code DrawingPanel} using a lambda function. For example:
*
* <pre>
* // example of attaching a mouse click handler using Java 8
* panel.onClick( (x, y) -> System.out.println(x + " " + y) );
* </pre>
* <h3>Debugging facilities (new in BJP 4th edition):</h3>
*
* <p>
* This version now includes an inner class named {@code DebuggingGraphics}
* that keeps track of how many times various drawing methods are called.
* It includes a {@code showCounts} method for the {@code DrawingPanel} itself
* that allows a client to examine this. The panel will record basic drawing
* methods performed by a version of the {@code Graphics} class obtained by
* calling {@code getDebuggingGraphics} :
*
* <pre>
* // example of debugging counts of graphics method calls
* Graphics g = panel.getDebuggingGraphics();
* </pre>
*
* <p>
* Novices will be encouraged to simply print it at the end of {@code main}, as in:
*
* <pre>
* System.out.println(panel.getCounts());
* </pre>
*
* <h3>History and recent changes:</h3>
*
* 2016/07/25
* - Added and cleaned up BJP4 features, static anti-alias settings, bug fixes.
* <p>
*
* 2016/03/07
* - Code cleanup and improvements to JavaDoc comments for BJP4 release.
* <p>
*
* 2015/09/04
* - Now includes methods for get/setting individual pixels and all pixels on the
* drawing panel. This helps facilitate 2D array-based pixel-processing
* exercises and problems for Building Java Programs, 4th edition.
* - Code cleanup and reorganization.
* Now better alphabetization/formatting of members and encapsulation.
* Commenting also augmented throughout code.
* <p>
*
* 2015/04/09
* - Now includes a DebuggingGraphics inner class that keeps track of how many
* times various drawing methods are called.
* All additions are commented (search for "DebuggingGraphics")
* <p>
*
* 2011/10/25
* - save zoomed images (2011/10/25)
* <p>
*
* 2011/10/21
* - window no longer moves when zoom changes
* - grid lines
*
* @author Marty Stepp, Stanford University, and Stuart Reges, University of Washington
* @version 4.05, 2016/09/07 (BJP 4th edition)
*/
public class DrawingPanel implements ImageObserver {
// class constants
private static final Color GRID_LINE_COLOR = new Color(64, 64, 64, 128); // color of grid lines on panel
private static final Object LOCK = new Object(); // object used for concurrency locking
private static final boolean SAVE_SCALED_IMAGES = true; // if true, when panel is zoomed, saves images at that zoom factor
private static final int DELAY = 100; // delay between repaints in millis
private static final int MAX_FRAMES = 100; // max animation frames
private static final int MAX_SIZE = 10000; // max width/height
private static final int GRID_LINES_PX_GAP_DEFAULT = 10; // default px between grid lines
private static final String VERSION = "4.05 (2016/09/07)";
private static final String ABOUT_MESSAGE = "DrawingPanel\n"
+ "Graphical library class to support Building Java Programs textbook\n"
+ "written by Marty Stepp, Stanford University\n"
+ "and Stuart Reges, University of Washington\n\n"
+ "Version: " + VERSION + "\n\n"
+ "please visit our web site at:\n"
+ "http://www.buildingjavaprograms.com/";
private static final String ABOUT_MESSAGE_TITLE = "About DrawingPanel";
private static final String COURSE_WEB_SITE = "http://courses.cs.washington.edu/courses/cse142/CurrentQtr/drawingpanel.txt";
private static final String TITLE = "Drawing Panel";
/** An RGB integer representing alpha at 100% opacity (0xff000000). */
public static final int PIXEL_ALPHA = 0xff000000; // rgb integer for alpha 100% opacity
/** An RGB integer representing 100% blue (0x000000ff). */
public static final int PIXEL_BLUE = 0x000000ff; // rgb integer for 100% blue
/** An RGB integer representing 100% green (0x0000ff00). */
public static final int PIXEL_GREEN = 0x0000ff00; // rgb integer for 100% green
/** An RGB integer representing 100% red (0x00ff0000). */
public static final int PIXEL_RED = 0x00ff0000; // rgb integer for 100% red
/**
* The default width of a DrawingPanel in pixels, if none is supplied at construction (500 pixels).
*/
public static final int DEFAULT_WIDTH = 500;
/**
* The default height of a DrawingPanel in pixels, if none is supplied at construction (400 pixels).
*/
public static final int DEFAULT_HEIGHT = 400;
/** An internal constant for setting system properties; clients should not use this. */
public static final String ANIMATED_PROPERTY = "drawingpanel.animated";
/** An internal constant for setting system properties; clients should not use this. */
public static final String ANIMATION_FILE_NAME = "_drawingpanel_animation_save.txt";
/** An internal constant for setting system properties; clients should not use this. */
public static final String ANTIALIAS_PROPERTY = "drawingpanel.antialias";
/** An internal constant for setting system properties; clients should not use this. */
public static final String AUTO_ENABLE_ANIMATION_ON_SLEEP_PROPERTY = "drawingpanel.animateonsleep";
/** An internal constant for setting system properties; clients should not use this. */
public static final String DIFF_PROPERTY = "drawingpanel.diff";
/** An internal constant for setting system properties; clients should not use this. */
public static final String HEADLESS_PROPERTY = "drawingpanel.headless";
/** An internal constant for setting system properties; clients should not use this. */
public static final String MULTIPLE_PROPERTY = "drawingpanel.multiple";
/** An internal constant for setting system properties; clients should not use this. */
public static final String SAVE_PROPERTY = "drawingpanel.save";
/* a list of all DrawingPanel instances ever created; used for saving graphical output */
private static final List<DrawingPanel> INSTANCES = new ArrayList<DrawingPanel>();
// static variables
private static boolean DEBUG = false;
private static int instances = 0;
private static String saveFileName = null;
private static Boolean headless = null;
private static Boolean antiAliasDefault = true;
private static Thread shutdownThread = null;
// static class initializer - sets up thread to close program if
// last DrawingPanel is closed
static {
try {
String debugProp = String.valueOf(System.getProperty("drawingpanel.debug")).toLowerCase();
DEBUG = DEBUG || "true".equalsIgnoreCase(debugProp)
|| "on".equalsIgnoreCase(debugProp)
|| "yes".equalsIgnoreCase(debugProp)
|| "1".equals(debugProp);
} catch (Throwable t) {
// empty
}
}
/*
* Called when DrawingPanel class loads up.
* Checks whether the user wants to save an animation to a file.
*/
private static void checkAnimationSettings() {
try {
File settingsFile = new File(ANIMATION_FILE_NAME);
if (settingsFile.exists()) {
Scanner input = new Scanner(settingsFile);
String animationSaveFileName = input.nextLine();
input.close();
System.out.println("***");
System.out.println("*** DrawingPanel saving animated GIF: " +
new File(animationSaveFileName).getName());
System.out.println("***");
settingsFile.delete();
System.setProperty(ANIMATED_PROPERTY, "1");
System.setProperty(SAVE_PROPERTY, animationSaveFileName);
}
} catch (Exception e) {
if (DEBUG) {
System.out.println("error checking animation settings: " + e);
}
}
}
/*
* Helper that throws an IllegalArgumentException if the given integer
* is not between the given min-max inclusive
*/
private static void ensureInRange(String name, int value, int min, int max) {
if (value < min || value > max) {
throw new IllegalArgumentException(name + " must be between " + min
+ " and " + max + ", but saw " + value);
}
}
/*
* Helper that throws a NullPointerException if the given value is null
*/
private static void ensureNotNull(String name, Object value) {
if (value == null) {
throw new NullPointerException("null value was passed for " + name);
}
}
/**
* Returns the alpha (opacity) component of the given RGB pixel from 0-255.
* Often used in conjunction with the methods getPixelRGB, setPixelRGB, etc.
* @param rgb RGB integer with alpha in bits 0-7, red in bits 8-15, green in
* bits 16-23, and blue in bits 24-31
* @return alpha component from 0-255
*/
public static int getAlpha(int rgb) {
return (rgb & 0xff000000) >> 24;
}
/**
* Returns the blue component of the given RGB pixel from 0-255.
* Often used in conjunction with the methods getPixelRGB, setPixelRGB, etc.
* @param rgb RGB integer with alpha in bits 0-7, red in bits 8-15, green in
* bits 16-23, and blue in bits 24-31
* @return blue component from 0-255
*/
public static int getBlue(int rgb) {
return (rgb & 0x000000ff);
}
/**
* Returns the green component of the given RGB pixel from 0-255.
* Often used in conjunction with the methods getPixelRGB, setPixelRGB, etc.
* @param rgb RGB integer with alpha in bits 0-7, red in bits 8-15, green in
* bits 16-23, and blue in bits 24-31
* @return green component from 0-255
*/
public static int getGreen(int rgb) {
return (rgb & 0x0000ff00) >> 8;
}
/**
* Returns the red component of the given RGB pixel from 0-255.
* Often used in conjunction with the methods getPixelRGB, setPixelRGB, etc.
* @param rgb RGB integer with alpha in bits 0-7, red in bits 8-15, green in
* bits 16-23, and blue in bits 24-31
* @return red component from 0-255
*/
public static int getRed(int rgb) {
return (rgb & 0x00ff0000) >> 16;
}
/*
* Returns the given Java system property as a Boolean.
* Note uppercase-B meaning that if the property isn't set, this will return null.
* That also means that if you call it and try to store as lowercase-B boolean and
* it's null, you will crash the program. You have been warned.
*/
private static Boolean getPropertyBoolean(String name) {
try {
String prop = System.getProperty(name);
if (prop == null) {
return null;
} else {
return name.equalsIgnoreCase("true")
|| name.equals("1")
|| name.equalsIgnoreCase("on")
|| name.equalsIgnoreCase("yes");
}
} catch (SecurityException e) {
if (DEBUG) System.out.println("Security exception when trying to read " + name);
return null;
}
}
/**
* Returns the file name used for saving all DrawingPanel instances.
* By default this is null, but it can be set using setSaveFileName
* or by setting the SAVE_PROPERTY env variable.
* @return the shared save file name
*/
public static String getSaveFileName() {
if (saveFileName == null) {
try {
saveFileName = System.getProperty(SAVE_PROPERTY);
} catch (SecurityException e) {
// empty
}
}
return saveFileName;
}
/*
* Returns whether the given Java system property has been set.
*/
private static boolean hasProperty(String name) {
try {
return System.getProperty(name) != null;
} catch (SecurityException e) {
if (DEBUG) System.out.println("Security exception when trying to read " + name);
return false;
}
}
/**
* Returns true if DrawingPanel instances should anti-alias (smooth) their graphics.
* By default this is true, but it can be set to false using the ANTIALIAS_PROPERTY.
* @return true if anti-aliasing is enabled (default true)
*/
public static boolean isAntiAliasDefault() {
if (antiAliasDefault != null) {
return antiAliasDefault;
} else if (hasProperty(ANTIALIAS_PROPERTY)) {
return getPropertyBoolean(ANTIALIAS_PROPERTY);
} else {
return true; // default
}
}
/**
* Returns true if the class is in "headless" mode, meaning that it is running on
* a server without a graphical user interface.
* @return true if we are in headless mode (default false)
*/
public static boolean isHeadless() {
if (headless != null) {
return headless;
} else {
return hasProperty(HEADLESS_PROPERTY) && getPropertyBoolean(HEADLESS_PROPERTY);
}
}
/**
* Internal method; returns whether the 'main' thread is still running.
* Used to determine whether to exit the program when the drawing panel
* is closed by the user.
* This is an internal method not meant to be called by clients.
* @return true if main thread is still running
*/
public static boolean mainIsActive() {
ThreadGroup group = Thread.currentThread().getThreadGroup();
int activeCount = group.activeCount();
// look for the main thread in the current thread group
Thread[] threads = new Thread[activeCount];
group.enumerate(threads);
for (int i = 0; i < threads.length; i++) {
Thread thread = threads[i];
String name = String.valueOf(thread.getName()).toLowerCase();
if (DEBUG) System.out.println(" DrawingPanel.mainIsActive(): " + thread.getName() + ", priority=" + thread.getPriority() + ", alive=" + thread.isAlive() + ", stack=" + java.util.Arrays.toString(thread.getStackTrace()));
if (name.indexOf("main") >= 0 ||
name.indexOf("testrunner-assignmentrunner") >= 0) {
// found main thread!
// (TestRunnerApplet's main runner also counts as "main" thread)
return thread.isAlive();
}
}
// didn't find a running main thread; guess that main is done running
return false;
}
/*
* Returns whether the given Java system property has been set to a
* "truthy" value such as "yes" or "true" or "1".
*/
private static boolean propertyIsTrue(String name) {
try {
String prop = System.getProperty(name);
return prop != null && (prop.equalsIgnoreCase("true")
|| prop.equalsIgnoreCase("yes")
|| prop.equalsIgnoreCase("1"));
} catch (SecurityException e) {
if (DEBUG) System.out.println("Security exception when trying to read " + name);
return false;
}
}
/**
* Saves every DrawingPanel instance that is active.
* @throws IOException if unable to save any of the files.
*/
public static void saveAll() throws IOException {
for (DrawingPanel panel : INSTANCES) {
if (!panel.hasBeenSaved) {
panel.save(getSaveFileName());
}
}
}
/**
* Sets whether DrawingPanel instances should anti-alias (smooth) their pixels by default.
* Default true. You can set this on a given DrawingPanel instance with setAntialias(boolean).
* @param value whether to enable anti-aliasing (default true)
*/
public static void setAntiAliasDefault(Boolean value) {
antiAliasDefault = value;
}
/**
* Sets the class to run in "headless" mode, with no graphical output on screen.
* @param value whether to enable headless mode (default false)
*/
public static void setHeadless(Boolean value) {
headless = value;
if (headless != null) {
if (headless) {
// Set up Java AWT graphics configuration so that it can draw in 'headless' mode
// (without popping up actual graphical windows on the server's monitor)
// creating the buffered image below will prep the classloader so that Image
// classes are available later to the JVM
System.setProperty("java.awt.headless", "true");
java.awt.image.BufferedImage img = new java.awt.image.BufferedImage(100, 100, java.awt.image.BufferedImage.TYPE_INT_RGB);
img.getGraphics().drawRect(10, 20, 30, 40);
} else {
System.setProperty("java.awt.headless", "false");
}
}
}
/**
* Sets the file to be used when saving graphical output for all DrawingPanels.
* @param file the file to use as default save file
*/
public static void setSaveFile(File file) {
setSaveFileName(file.toString());
}
/**
* Sets the filename to be used when saving graphical output for all DrawingPanels.
* @param filename the name/path of the file to use as default save file
*/
public static void setSaveFileName(String filename) {
try {
System.setProperty(SAVE_PROPERTY, filename);
} catch (SecurityException e) {
// empty
}
saveFileName = filename;
}
/**
* Returns an RGB integer made from the given red, green, and blue components
* from 0-255. The returned integer is suitable for use with various RGB
* integer methods in this class such as setPixel.
* @param r red component from 0-255 (bits 8-15)
* @param g green component from 0-255 (bits 16-23)
* @param b blue component from 0-255 (bits 24-31)
* @return RGB integer with full 255 for alpha and r-g-b in bits 8-31
* @throws IllegalArgumentException if r, g, or b is not in 0-255 range
*/
public static int toRgbInteger(int r, int g, int b) {
return toRgbInteger(/* alpha */ 255, r, g, b);
}
/**
* Returns an RGB integer made from the given alpha, red, green, and blue components
* from 0-255. The returned integer is suitable for use with various RGB
* integer methods in this class such as setPixel.
* @param alpha alpha (transparency) component from 0-255 (bits 0-7)
* @param r red component from 0-255 (bits 8-15)
* @param g green component from 0-255 (bits 16-23)
* @param b blue component from 0-255 (bits 24-31)
* @return RGB integer with the given four components
* @throws IllegalArgumentException if alpha, r, g, or b is not in 0-255 range
*/
public static int toRgbInteger(int alpha, int r, int g, int b) {
ensureInRange("alpha", alpha, 0, 255);
ensureInRange("red", r, 0, 255);
ensureInRange("green", g, 0, 255);
ensureInRange("blue", b, 0, 255);
return ((alpha & 0x000000ff) << 24)
| ((r & 0x000000ff) << 16)
| ((g & 0x000000ff) << 8)
| ((b & 0x000000ff));
}
/*
* Returns whether the current program is running in the DrJava editor.
* This was needed in the past because DrJava messed with some settings.
*/
private static boolean usingDrJava() {
try {
return System.getProperty("drjava.debug.port") != null ||
System.getProperty("java.class.path").toLowerCase().indexOf("drjava") >= 0;
} catch (SecurityException e) {
// running as an applet, or something
return false;
}
}
// fields
private ActionListener actionListener;
private List<ImageFrame> frames; // stores frames of animation to save
private boolean animated = false; // changes to true if sleep() is called
private boolean antialias = isAntiAliasDefault(); // true to smooth corners of shapes
private boolean gridLines = false; // grid lines every 10px on screen
private boolean hasBeenSaved = false; // set true once saved to file (to avoid re-saving same panel)
private BufferedImage image; // remembers drawing commands
private Color backgroundColor = Color.WHITE;
private Gif89Encoder encoder; // for saving animations
private Graphics g3; // new field to support DebuggingGraphics
private Graphics2D g2; // graphics context for painting
private ImagePanel imagePanel; // real drawing surface
private int currentZoom = 1; // panel's zoom factor for drawing
private int gridLinesPxGap = GRID_LINES_PX_GAP_DEFAULT; // px between grid lines
private int initialPixel; // initial value in each pixel, for clear()
private int instanceNumber; // every DPanel has a unique number
private int width; // dimensions of window frame
private int height; // dimensions of window frame
private JFileChooser chooser; // file chooser to save files
private JFrame frame; // overall window frame
private JLabel statusBar; // status bar showing mouse position
private JPanel panel; // overall drawing surface
private long createTime; // time at which DrawingPanel was constructed
private Map<String, Integer> counts; // new field to support DebuggingGraphics
private MouseInputListener mouseListener;
private String callingClassName; // name of class that constructed this panel
private Timer timer; // animation timer
private WindowListener windowListener;
/**
* Constructs a drawing panel with a default width and height enclosed in a window.
* Uses DEFAULT_WIDTH and DEFAULT_HEIGHT for the panel's size.
*/
public DrawingPanel() {
this(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
/**
* Constructs a drawing panel of given width and height enclosed in a window.
* @param width panel's width in pixels
* @param height panel's height in pixels
*/
public DrawingPanel(int width, int height) {
ensureInRange("width", width, 0, MAX_SIZE);
ensureInRange("height", height, 0, MAX_SIZE);
checkAnimationSettings();
if (DEBUG) System.out.println("DrawingPanel(): going to grab lock");
synchronized (LOCK) {
instances++;
instanceNumber = instances; // each DrawingPanel stores its own int number
INSTANCES.add(this);
if (shutdownThread == null && !usingDrJava()) {
if (DEBUG) System.out.println("DrawingPanel(): starting idle thread");
shutdownThread = new Thread(new Runnable() {
// Runnable implementation; used for shutdown thread.
public void run() {
boolean save = shouldSave();
try {
while (true) {
// maybe shut down the program, if no more DrawingPanels are onscreen
// and main has finished executing
save |= shouldSave();
if (DEBUG) System.out.println("DrawingPanel idle thread: instances=" + instances + ", save=" + save + ", main active=" + mainIsActive());
if ((instances == 0 || save) && !mainIsActive()) {
try {
System.exit(0);
} catch (SecurityException sex) {
if (DEBUG) System.out.println("DrawingPanel idle thread: unable to exit program: " + sex);
}
}
Thread.sleep(250);
}
} catch (Exception e) {
if (DEBUG) System.out.println("DrawingPanel idle thread: exception caught: " + e);
}
}
});
// shutdownThread.setPriority(Thread.MIN_PRIORITY);
shutdownThread.setName("DrawingPanel-shutdown");
shutdownThread.start();
}
}
this.width = width;
this.height = height;
if (DEBUG) System.out.println("DrawingPanel(w=" + width + ",h=" + height + ",anim=" + isAnimated() + ",graph=" + isGraphical() + ",save=" + shouldSave());
if (isAnimated() && shouldSave()) {
// image must be no more than 256 colors
image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED);
// image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
antialias = false; // turn off anti-aliasing to save palette colors
// initially fill the entire frame with the background color,
// because it won't show through via transparency like with a full ARGB image
Graphics g = image.getGraphics();
g.setColor(backgroundColor);
g.fillRect(0, 0, width + 1, height + 1);
} else {
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
initialPixel = image.getRGB(0, 0);
g2 = (Graphics2D) image.getGraphics();
// new field assignments for DebuggingGraphics
g3 = new DebuggingGraphics();
counts = new TreeMap<String, Integer>();
g2.setColor(Color.BLACK);
if (antialias) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
if (isAnimated()) {
initializeAnimation();
}
if (isGraphical()) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
// empty
}
statusBar = new JLabel(" ");
statusBar.setBorder(BorderFactory.createLineBorder(Color.BLACK));
panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.setBackground(backgroundColor);
panel.setPreferredSize(new Dimension(width, height));
imagePanel = new ImagePanel(image);
imagePanel.setBackground(backgroundColor);
panel.add(imagePanel);
// listen to mouse movement
mouseListener = new DPMouseListener();
panel.addMouseMotionListener(mouseListener);
// main window frame
frame = new JFrame(TITLE);
// frame.setResizable(false);
windowListener = new DPWindowListener();
frame.addWindowListener(windowListener);
// JPanel center = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
JScrollPane center = new JScrollPane(panel);
// center.add(panel);
frame.getContentPane().add(center);
frame.getContentPane().add(statusBar, "South");
frame.setBackground(Color.DARK_GRAY);
// menu bar
actionListener = new DPActionListener();
setupMenuBar();
frame.pack();
center(frame);
frame.setVisible(true);
if (!shouldSave()) {
toFront(frame);
}
// repaint timer so that the screen will update
createTime = System.currentTimeMillis();
timer = new Timer(DELAY, actionListener);
timer.start();
} else if (shouldSave()) {
// headless mode; just set a hook on shutdown to save the image
callingClassName = getCallingClassName();
try {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
// run on shutdown to save the image
public void run() {
if (DEBUG) System.out.println("DrawingPanel.run(): Running shutdown hook");
if (DEBUG) System.out.println("DrawingPanel shutdown hook: instances=" + instances);
try {
String filename = System.getProperty(SAVE_PROPERTY);
if (filename == null) {
filename = callingClassName + ".png";
}
if (isAnimated()) {
saveAnimated(filename);
} else {
save(filename);
}
} catch (SecurityException e) {
System.err.println("Security error while saving image: " + e);
} catch (IOException e) {
System.err.println("Error saving image: " + e);
}
}
}));
} catch (Exception e) {
if (DEBUG) System.out.println("DrawingPanel(): unable to add shutdown hook: " + e);
}
}
}
/**
* Constructs a drawing panel that displays the image from the given file enclosed in a window.
* The panel will be sized exactly to fit the image inside it.
* @param imageFile the image file to load
* @throws RuntimeException if the image file is not found
*/
public DrawingPanel(File imageFile) {
this(imageFile.toString());
}
/**
* Constructs a drawing panel that displays the image from the given file name enclosed in a window.
* The panel will be sized exactly to fit the image inside it.
* @param imageFileName the file name/path of the image file to load
* @throws RuntimeException if the image file is not found
*/
public DrawingPanel(String imageFileName) {
this();
Image image = loadImage(imageFileName);
setSize(image.getWidth(this), image.getHeight(this));
getGraphics().drawImage(image, 0, 0, this);
}
/**
* Adds the given event listener to respond to key events on this panel.
* @param listener the key event listener to attach
*/
public void addKeyListener(KeyListener listener) {
ensureNotNull("listener", listener);
frame.addKeyListener(listener);
panel.setFocusable(false);
frame.requestFocusInWindow();
frame.requestFocus();
}
/**
* Adds the given event listener to respond to mouse events on this panel.
* @param listener the mouse event listener to attach
*/
public void addMouseListener(MouseListener listener) {
ensureNotNull("listener", listener);
if (listener instanceof MouseMotionListener) {
panel.addMouseMotionListener((MouseMotionListener) listener);
}
}
/*
* Whether the panel should automatically switch to animated mode
* if it calls the sleep method.
*/
private boolean autoEnableAnimationOnSleep() {
return propertyIsTrue(AUTO_ENABLE_ANIMATION_ON_SLEEP_PROPERTY);
}
/*
* Moves the given JFrame to the center of the screen.
*/
private void center(Window frame) {
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screen = tk.getScreenSize();
int x = Math.max(0, (screen.width - frame.getWidth()) / 2);
int y = Math.max(0, (screen.height - frame.getHeight()) / 2);
frame.setLocation(x, y);
}
/*
* Constructs and initializes our JFileChooser field if necessary.
*/
private void checkChooser() {
if (chooser == null) {
chooser = new JFileChooser();
try {
chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
} catch (Exception e) {
// empty
}
chooser.setMultiSelectionEnabled(false);
chooser.setFileFilter(new DPFileFilter());
}
}
/**
* Erases all drawn shapes/lines/colors from the panel.
*/