-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDrawingPanel.java
More file actions
4013 lines (3544 loc) · 155 KB
/
DrawingPanel.java
File metadata and controls
4013 lines (3544 loc) · 155 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
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
* =====================================================================
*
* author: Marty Stepp, Stanford University
* author: Stuart Reges, University of Washington
* version: 2016/03/07 (BJP 4th edition)
*
* 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.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.java <br>
* Simplified Java drawing window class <br>
* to accompany Building Java Programs textbook and associated materials <br>
* ==========================================================================
*
* @author Marty Stepp and Stuart Reges, University of Washington
* @version 2016/03/07 (BJP 4th edition)
*
* <p>
* 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.
* </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 java.awt.Graphics
* object, and therefore most of the experience gained while using this library
* will transfer to Java graphics programming in other contexts.
* DrawingPanel is not intended to be a full rich graphical library for things
* like object-oriented drawing of shapes, animations, creating games, etc.
* </p>
* <p>
* Example usage:
* </p>
* <pre>
* DrawingPanel panel = new DrawingPanel(600, 400);
* Graphics g = panel.getGraphics();
* g.setColor(Color.RED);
* g.fillRect(17, 45, 139, 241);
* ...
* </pre>
* <p>
* To ensure that the image is always displayed, a timer calls repaint at
* regular intervals.
* </p>
* <p>
* This version of DrawingPanel also saves animated GIFs, though this is kind
* of hit-and-miss because animated GIFs are pretty sucky (256 color limit, large
* file size, etc).
* </p>
* <p>
* History and recent changes:
* </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. It includes a showCounts method
* for the DrawingPanel itself that allows a client to examine this. The
* panel will record basic drawing methods performed by a version of the
* Graphics class obtained by calling getDebugging Graphics:
*
* Graphics g = panel.getDebuggingGraphics();
*
* Novices will be encouraged to simply print it at the end of main, as in:
*
* System.out.println(panel.getCounts());
*
* 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
*/
public final class DrawingPanel implements ImageObserver {
// class constants
private static final Color GRID_LINE_COLOR = new Color(64, 64, 64, 128);
private static final Object LOCK = new Object();
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 GRID_SIZE = 10; // 10px between grid lines
private static final int MAX_FRAMES = 100; // max animation frames
private static final int MAX_SIZE = 10000; // max width/height
public static final int PIXEL_ALPHA = 0xff000000; // rgb integer for alpha 100% opacity
public static final int PIXEL_BLUE = 0x000000ff; // rgb integer for 100% blue
public static final int PIXEL_GREEN = 0x0000ff00; // rgb integer for 100% green
public static final int PIXEL_RED = 0x00ff0000; // rgb integer for 100% red
private static final String VERSION = "2016/03/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";
public static final String ANIMATED_PROPERTY = "drawingpanel.animated";
public static final String ANIMATION_FILE_NAME = "_drawingpanel_animation_save.txt";
public static final String AUTO_ENABLE_ANIMATION_ON_SLEEP_PROPERTY = "drawingpanel.animateonsleep";
public static final String DIFF_PROPERTY = "drawingpanel.diff";
public static final String HEADLESS_PROPERTY = "drawingpanel.headless";
public static final String MULTIPLE_PROPERTY = "drawingpanel.multiple";
public static final String SAVE_PROPERTY = "drawingpanel.save";
// static variables
private static boolean DEBUG = false;
private static int instances = 0;
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);
}
}
}
/**
* Returns the red component of the given RGB pixel from 0-255.
* Often used in conjunction with the methods getPixelRGB, setPixelRGB, etc.
*/
public static int getRed(int rgb) {
return (rgb & 0x00ff0000) >> 16;
}
/**
* Returns the green component of the given RGB pixel from 0-255.
* Often used in conjunction with the methods getPixelRGB, setPixelRGB, etc.
*/
public static int getGreen(int rgb) {
return (rgb & 0x0000ff00) >> 8;
}
/**
* Returns the blue component of the given RGB pixel from 0-255.
* Often used in conjunction with the methods getPixelRGB, setPixelRGB, etc.
*/
public static int getBlue(int rgb) {
return (rgb & 0x000000ff);
}
/**
* Returns the alpha (opacity) component of the given RGB pixel from 0-255.
* Often used in conjunction with the methods getPixelRGB, setPixelRGB, etc.
*/
public static int getAlpha(int rgb) {
return (rgb & 0xff000000) >> 24;
}
/*
* 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 whether the 'main' thread is still running.
* Used to determine whether to exit the program when the drawing panel
* is closed by the user.
*/
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;
}
}
/**
* 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.
*/
public static int toRgbInteger(int r, int g, int b) {
return 0xff000000
| ((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 ArrayList<ImageFrame> frames; // stores frames of animation to save
private boolean animated = false; // changes to true if sleep() is called
private boolean antialias = true; // true to smooth corners of shapes
private boolean gridLines = false; // grid lines every 10px on screen
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;
private int initialPixel; // initial value in each pixel, for clear()
private int instanceNumber; // every DPanel has a unique number
private int width, 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 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) {
if (width < 0 || width > MAX_SIZE || height < 0 || height > MAX_SIZE) {
throw new IllegalArgumentException("Illegal width/height: " + width + " x " + height);
}
checkAnimationSettings();
if (DEBUG) System.out.println("DrawingPanel(): going to grab lock");
synchronized (LOCK) {
instances++;
instanceNumber = instances; // each DrawingPanel stores its own int number
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);
}
}
}
/**
* Adds the given event listener to respond to key events on this panel.
*/
public void addKeyListener(KeyListener listener) {
frame.addKeyListener(listener);
panel.setFocusable(false);
frame.requestFocusInWindow();
frame.requestFocus();
}
/**
* Adds the given event listener to respond to mouse events on this panel.
*/
public void addMouseListener(MouseListener listener) {
panel.addMouseListener(listener);
if (listener instanceof MouseMotionListener) {
panel.addMouseMotionListener((MouseMotionListener) listener);
}
}
/**
* Adds the given event listener to respond to mouse events on this panel.
*/
// public void addMouseListener(MouseMotionListener listener) {
// panel.addMouseMotionListener(listener);
// if (listener instanceof MouseListener) {
// panel.addMouseListener((MouseListener) listener);
// }
// }
// /**
// * Adds the given event listener to respond to mouse events on this panel.
// */
// public void addMouseListener(MouseInputListener listener) {
// addMouseListener((MouseListener) 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.
*/
public void clear() {
int[] pixels = new int[width * height];
for (int i = 0; i < pixels.length; i++) {
pixels[i] = initialPixel;
}
image.setRGB(0, 0, width, height, pixels, 0, 1);
}
/*
* Compares the current DrawingPanel image to an image file on disk.
*/
private void compareToFile() {
// save current image to a temp file
try {
String tempFile = saveToTempFile();
// use file chooser dialog to find image to compare against
checkChooser();
if (chooser.showOpenDialog(frame) != JFileChooser.APPROVE_OPTION) {
return;
}
// user chose a file; let's diff it
new DiffImage(chooser.getSelectedFile().toString(), tempFile);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(frame,
"Unable to compare images: \n" + ioe);
}
}
/*
* Compares the current DrawingPanel image to an image file on the web.
*/
private void compareToURL() {
// save current image to a temp file
try {
String tempFile = saveToTempFile();
// get list of images to compare against from web site
URL url = new URL(COURSE_WEB_SITE);
Scanner input = new Scanner(url.openStream());
List<String> lines = new ArrayList<String>();
List<String> filenames = new ArrayList<String>();
while (input.hasNextLine()) {
String line = input.nextLine().trim();
if (line.length() == 0) { continue; }
if (line.startsWith("#")) {
// a comment
if (line.endsWith(":")) {
// category label
lines.add(line);
line = line.replaceAll("#\\s*", "");
filenames.add(line);
}
} else {
lines.add(line);
// get filename
int lastSlash = line.lastIndexOf('/');
if (lastSlash >= 0) {
line = line.substring(lastSlash + 1);
}
// remove extension
int dot = line.lastIndexOf('.');
if (dot >= 0) {
line = line.substring(0, dot);
}
filenames.add(line);
}
}
input.close();
if (filenames.isEmpty()) {
JOptionPane.showMessageDialog(frame,
"No valid web files found to compare against.",
"Error: no web files found",
JOptionPane.ERROR_MESSAGE);
return;
} else {
String fileURL = null;
if (filenames.size() == 1) {
// only one choice; take it
fileURL = lines.get(0);
} else {
// user chooses file to compare against
int choice = showOptionDialog(frame, "File to compare against?",
"Choose File", filenames.toArray(new String[0]));
if (choice < 0) {
return;
}
// user chose a file; let's diff it
fileURL = lines.get(choice);
}
new DiffImage(fileURL, tempFile);
}
} catch (NoRouteToHostException nrthe) {
JOptionPane.showMessageDialog(frame, "You do not appear to have a working internet connection.\nPlease check your internet settings and try again.\n\n" + nrthe);
} catch (UnknownHostException uhe) {
JOptionPane.showMessageDialog(frame, "Internet connection error: \n" + uhe);
} catch (SocketException se) {
JOptionPane.showMessageDialog(frame, "Internet connection error: \n" + se);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(frame, "Unable to compare images: \n" + ioe);
}
}
/*
* Closes the DrawingPanel and exits the program.
*/
private void exit() {
if (isGraphical()) {
frame.setVisible(false);
frame.dispose();
}
try {
System.exit(0);
} catch (SecurityException e) {
// if we're running in an applet or something, can't do System.exit
}
}
/*
* Returns a best guess about the name of the class that constructed this panel.
*/
private String getCallingClassName() {
StackTraceElement[] stack = new RuntimeException().getStackTrace();
String className = this.getClass().getName();
for (StackTraceElement element : stack) {
String cl = element.getClassName();
if (!className.equals(cl)) {
className = cl;
break;
}
}
return className;
}
/**
* Returns an immutable version of the internal map used for counting
* occurrences calls on various drawing methods. Experts can manipulate
* the map, but novices will be encouraged to simply print it.
*/
public Map<String, Integer> getCounts() {
return Collections.unmodifiableMap(counts);
}
/**
* A variation of getGraphics that returns an object that records
* a count for various drawing methods.
* See also: getCounts.
*/
public Graphics getDebuggingGraphics() {
if (g3 == null) {
g3 = new DebuggingGraphics();
}
return g3;
}
/**
* Obtain the Graphics object to draw on the panel.
*/
public Graphics2D getGraphics() {
return g2;
}
/*
* Creates the buffered image for drawing on this panel.
*/
private BufferedImage getImage() {
// create second image so we get the background color
BufferedImage image2;
if (isAnimated()) {
image2 = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED);
} else {
image2 = new BufferedImage(width, height, image.getType());
}
Graphics g = image2.getGraphics();
// if (DEBUG) System.out.println("DrawingPanel getImage setting background to " + backgroundColor);
g.setColor(backgroundColor);
g.fillRect(0, 0, width, height);
g.drawImage(image, 0, 0, panel);
return image2;
}
/**
* Returns the drawing panel's height in pixels.
*/
public int getHeight() {
return height;
}
/**
* Returns the color of the pixel at the given x/y coordinate as a Color object.
* If nothing has been explicitly drawn on this particular pixel, the panel's
* background color is returned.
*/
public Color getPixel(int x, int y) {
int rgb = getPixelRGB(x, y);
if (getAlpha(rgb) == 0) {
return backgroundColor;
} else {
return new Color(rgb, /* hasAlpha */ true);
}
}
/**
* Returns the color of the pixel at the given x/y coordinate as an RGB integer.
* The individual red, green, and blue components of the RGB integer can be
* extracted from this by calling DrawingPanel.getRed, getGreen, and getBlue.
* If nothing has been explicitly drawn on this particular pixel, the panel's
* background color is returned.
* See also: getPixel.
*/
public int getPixelRGB(int x, int y) {
int rgb = image.getRGB(x, y);
if (getAlpha(rgb) == 0) {
return backgroundColor.getRGB();
} else {
return rgb;
}
}
/**
* Returns the colors of all pixels in this DrawingPanel as a 2-D array
* of Color objects.
* The first index of the array is the y-coordinate, and the second index
* is the x-coordinate. So, for example, index [r][c] represents the RGB
* pixel data for the pixel at position (x=c, y=r).
*/
public Color[][] getPixels() {
Color[][] pixels = new Color[getHeight()][getWidth()];
for (int row = 0; row < pixels.length; row++) {
for (int col = 0; col < pixels[0].length; col++) {
// note axis inversion; x/y => col/row
pixels[row][col] = getPixel(col, row);
}
}
return pixels;
}
/**
* Returns the colors of all pixels in this DrawingPanel as a 2-D array
* of RGB integers.
* The first index of the array is the y-coordinate, and the second index
* is the x-coordinate. So, for example, index [r][c] represents the RGB
* pixel data for the pixel at position (x=c, y=r).
* The individual red, green, and blue components of each RGB integer can be
* extracted from this by calling DrawingPanel.getRed, getGreen, and getBlue.
*/
public int[][] getPixelsRGB() {
int[][] pixels = new int[getHeight()][getWidth()];
int backgroundRGB = backgroundColor.getRGB();
for (int row = 0; row < pixels.length; row++) {
for (int col = 0; col < pixels[0].length; col++) {
// note axis inversion; x/y => col/row
int px = image.getRGB(col, row);
if (getAlpha(px) == 0) {
pixels[col][row] = backgroundRGB;
} else {
pixels[col][row] = px;
}
}
}
return pixels;
}
/**
* Returns the drawing panel's pixel size (width, height) as a Dimension object.
*/
public Dimension getSize() {
return new Dimension(width, height);
}
/**
* Returns the drawing panel's width in pixels.
*/
public int getWidth() {
return width;
}
/**
* Returns the drawing panel's current zoom factor.
* Initially this is 1 to indicate 100% zoom, the original size.
*/
public int getZoom() {
return currentZoom;
}
/**
* Required method of ImageObserver interface.
* Notifies the panel when images are loaded and updated.
*/
@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
imagePanel.imageUpdate(img, infoflags, x, y, width, height);
return false;
}
/*
* Sets up state for drawing and saving frames of animation to a GIF image.
*/
private void initializeAnimation() {
frames = new ArrayList<ImageFrame>();
encoder = new Gif89Encoder();
/*
try {
if (hasProperty(SAVE_PROPERTY)) {
stream = new FileOutputStream(System.getProperty(SAVE_PROPERTY));
}
// encoder.startEncoding(stream);
} catch (IOException e) {
System.out.println(e);
}
*/
}
/*
* Returns whether this drawing panel is in animation mode.
*/
private boolean isAnimated() {
return animated || propertyIsTrue(ANIMATED_PROPERTY);
}
/*
* Returns whether this drawing panel is going to be displayed on screen.
* This is almost always true except in some server environments where
* the DrawingPanel is run 'headless' without a GUI, often for scripting
* and automation purposes.
*/
private boolean isGraphical() {
return !hasProperty(SAVE_PROPERTY) && !hasProperty(HEADLESS_PROPERTY);
}
/*
* Returns true if the drawing panel class is in multiple mode.
* This would be true if the current program pops up several drawing panels
* and we want to save the state of each of them to a different file.
*/
private boolean isMultiple() {
return propertyIsTrue(MULTIPLE_PROPERTY);
}
/**