-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathDrawingPanel.java
More file actions
2870 lines (2674 loc) · 93.4 KB
/
DrawingPanel.java
File metadata and controls
2870 lines (2674 loc) · 93.4 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
/*
* Open Source Physics software is free software as described near the bottom of this code file.
*
* For additional information and documentation on Open Source Physics please see:
* <http://www.opensourcephysics.org/>
*/
package org.opensourcephysics.display;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.KeyboardFocusManager;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.MouseInputAdapter;
import javax.swing.text.JTextComponent;
import org.opensourcephysics.controls.OSPLog;
import org.opensourcephysics.controls.XML;
import org.opensourcephysics.controls.XMLControl;
import org.opensourcephysics.display.axes.CoordinateStringBuilder;
import org.opensourcephysics.display.dialogs.DrawingPanelInspector;
import org.opensourcephysics.display.dialogs.ScaleInspector;
import org.opensourcephysics.display.dialogs.XMLDrawingPanelInspector;
import org.opensourcephysics.tools.FontSizer;
import org.opensourcephysics.tools.ToolsRes;
import org.opensourcephysics.tools.VideoTool;
/**
* DrawingPanel renders drawable objects on its canvas.
* DrawingPanel provides drawable objects with methods that transform from world
* coordinates to pixel coordinates. World coordinates are defined by xmin, xmax,
* ymin, and ymax. These values are recalculated on-the-fly from preferred
* values if the aspect ratio is unity; otherwise, preferred values are used.
*
* If xmax>xmin then the coordinate scale increases from right to left.
* If xmax<xmin then the coordinate scale increases from left to right.
* If ymax>ymin then the coordinate scale increases from bottom to top.
* If ymax<ymin then the coordinate scale increases from top to bottom.
*
* @author Wolfgang Christian
* @author Joshua Gould
* @version 1.0
*/
public class DrawingPanel extends JPanel implements ActionListener, Renderable {
static final boolean RECORD_PAINT_TIMES = false; // set true to test painting time
long currentTime = System.currentTimeMillis();
/** Message box location */
public static final int BOTTOM_LEFT = 0;
/** Message box location */
public static final int BOTTOM_RIGHT = 1;
/** Message box location */
public static final int TOP_RIGHT = 2;
/** Message box location */
public static final int TOP_LEFT = 3;
protected JPopupMenu popupmenu = new JPopupMenu(); // right mouse click popup menu
protected JMenuItem propertiesItem, autoscaleItem, scaleItem, zoomInItem, zoomOutItem, snapshotItem; // the menu item for the properites dialog box
protected int leftGutter = 0, topGutter = 0, rightGutter = 0, bottomGutter = 0;
protected int leftGutterPreferred = 0, topGutterPreferred = 0, rightGutterPreferred = 0, bottomGutterPreferred = 0;
protected boolean clipAtGutter = true; // clips the drawing at the gutter if true
protected boolean adjustableGutter = false; // adjust gutter depending on panel size
protected int width, height; // the size of the panel the last time it was painted.
protected Color bgColor = new Color(239, 239, 255); // background color
protected boolean antialiasTextOn = false;
protected boolean antialiasShapeOn = false;
protected boolean squareAspect = false; // adjust xAspect and yAspect so the drawing aspect ratio is unity
protected boolean autoscaleX = true;
protected boolean autoscaleY = true;
protected boolean autoscaleXMin = true, autoscaleXMax = true;
protected boolean autoscaleYMin = true, autoscaleYMax = true;
protected double autoscaleMargin = 0.0; // used to increase the autoscale range
// x and y scale in world units
protected double xminPreferred = -10.0, xmaxPreferred = 10.0;
protected double yminPreferred = -10.0, ymaxPreferred = 10.0;
protected double xfloor = Double.NaN, xceil = Double.NaN;
protected double yfloor = Double.NaN, yceil = Double.NaN;
protected double xmin = xminPreferred, xmax = xmaxPreferred;
protected double ymin = yminPreferred, ymax = xmaxPreferred;
// pixel scale parameters These are set every time paintComponent is called using the size of the panel
protected boolean fixedPixelPerUnit = false;
protected double xPixPerUnit = 1; // the x scale in pixels per unit
protected double yPixPerUnit = 1; // the y scale in pixels per unit
protected AffineTransform pixelTransform = new AffineTransform(); // transform from world to pixel coodinates.
protected double[] pixelMatrix = new double[6]; // 6 values in the 3x3 pixel transformation
protected ArrayList<Drawable> drawableList = new ArrayList<Drawable>(); // list of Drawable objects
private volatile boolean validImage = false; // true if the current image is valid, false otherwise
protected BufferedImage offscreenImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
protected BufferedImage workingImage = offscreenImage;
private boolean buffered = false; // true will draw this component using an off-screen image
protected TextPanel trMessageBox = new TextPanel(); // text box in top right hand corner for message
protected TextPanel tlMessageBox = new TextPanel(); // text box in top left hand corner for message
protected TextPanel brMessageBox = new TextPanel(); // text box in lower right hand corner for message
protected TextPanel blMessageBox = new TextPanel(); // text box in lower left hand corner for mouse coordinates
protected DecimalFormat scientificFormat = new DecimalFormat("0.###E0"); // coordinate display format for message box. //$NON-NLS-1$
protected DecimalFormat decimalFormat = new DecimalFormat("0.00"); // coordinate display format for message box. //$NON-NLS-1$
protected MouseInputAdapter mouseController = new CMController(); // handles the coordinate display on mouse actions
protected boolean showCoordinates = false; // set to true when mouse listener is added
protected MouseInputAdapter optionController = new OptionController(); // handles optional mouse actions
protected ZoomBox zoomBox = new ZoomBox();
protected boolean enableZoom = true; // scale can be set via a mouse drag
protected boolean fixedScale = false; // scale is fixed (not user-settable)
protected Window customInspector; // optional custom inspector for this panel
protected Dimensioned dimensionSetter = null;
protected Rectangle viewRect = null; // the clipping rectangle within a scroll pane viewport
// CoordinateStringBuilder converts a mouse event into a string that displays world coordinates.
protected CoordinateStringBuilder coordinateStrBuilder = CoordinateStringBuilder.createCartesian();
protected GlassPanel glassPanel = new GlassPanel();
protected OSPLayout glassPanelLayout = new OSPLayout();
int refreshDelay = 100; // time in ms to delay refresh events
javax.swing.Timer refreshTimer = new javax.swing.Timer(refreshDelay, this); // delay before for refreshing panel
VideoTool vidCap;
double imageRatio = 1.0;
protected double xLeftMarginPercentage = 0.0, xRightMarginPercentage = 0.0;
protected double yTopMarginPercentage = 0.0, yBottomMarginPercentage = 0.0;
boolean logScaleX = false; // set true if the this axis uses a logarithmic scale
boolean logScaleY = false; // set true if the this axis uses a logarithmic scale
int zoomDelay = 40, zoomCount;
javax.swing.Timer zoomTimer;
double dxmin, dxmax, dymin, dymax;
/**
* DrawingPanel constructor.
*/
public DrawingPanel() {
glassPanel.setLayout(glassPanelLayout);
super.setLayout(new BorderLayout());
glassPanel.add(trMessageBox, OSPLayout.TOP_RIGHT_CORNER);
glassPanel.add(tlMessageBox, OSPLayout.TOP_LEFT_CORNER);
glassPanel.add(brMessageBox, OSPLayout.BOTTOM_RIGHT_CORNER);
glassPanel.add(blMessageBox, OSPLayout.BOTTOM_LEFT_CORNER);
glassPanel.setOpaque(false);
super.add(glassPanel, BorderLayout.CENTER);
setBackground(bgColor);
setPreferredSize(new Dimension(300, 300));
showCoordinates = true; // show coordinates by default
addMouseListener(mouseController);
addMouseMotionListener(mouseController);
addOptionController();
// invalidate the buffered image if the size changes
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(ComponentEvent e) {
invalidateImage(); // validImage = false;
}
});
buildPopupmenu();
refreshTimer.setRepeats(false);
refreshTimer.setCoalesce(true);
setFontLevel(FontSizer.getLevel());
zoomTimer = new javax.swing.Timer(zoomDelay, new ActionListener() {
public void actionPerformed(ActionEvent e) {
// reset and hide the zoom box
zoomBox.xlast = zoomBox.xstop = zoomBox.xstart = 0;
zoomBox.ylast = zoomBox.ystop = zoomBox.ystart = 0;
zoomBox.visible = zoomBox.dragged = false;
int steps = 4;
if(zoomCount<steps) {
zoomCount++;
double xmin = getXMin()+dxmin/steps;
double xmax = getXMax()+dxmax/steps;
double ymin = getYMin()+dymin/steps;
double ymax = getYMax()+dymax/steps;
setPreferredMinMax(xmin, xmax, ymin, ymax);
repaint(); // repaint the panel with the new scale
} else {
zoomTimer.stop();
invalidateImage();
repaint();
}
}
});
zoomTimer.setInitialDelay(0);
// Changes font size
FontSizer.addPropertyChangeListener("level", new PropertyChangeListener() { //$NON-NLS-1$
public void propertyChange(PropertyChangeEvent e) {
int level = ((Integer) e.getNewValue()).intValue();
setFontLevel(level);
}
});
ToolsRes.addPropertyChangeListener("locale", new PropertyChangeListener() { //$NON-NLS-1$
public void propertyChange(PropertyChangeEvent e) {
refreshGUI();
}
});
}
/**
* Refreshes the user interface in response to display changes such as Language.
*/
protected void refreshGUI() {
zoomInItem.setText(DisplayRes.getString("DisplayPanel.Zoom_in_menu_item")); //$NON-NLS-1$
zoomOutItem.setText(DisplayRes.getString("DisplayPanel.Zoom_out_menu_item")); //$NON-NLS-1$
scaleItem.setText(DisplayRes.getString("DrawingFrame.Scale_menu_item")); //$NON-NLS-1$
autoscaleItem.setText(DisplayRes.getString("DrawingFrame.Autoscale_menu_item")); //$NON-NLS-1$
snapshotItem.setText(DisplayRes.getString("DisplayPanel.Snapshot_menu_item")); //$NON-NLS-1$
propertiesItem.setText(DisplayRes.getString("DrawingFrame.InspectMenuItem")); //$NON-NLS-1$
}
/**
* Sets the font level.
*
* @param level the level
*/
protected void setFontLevel(int level) {
Font font = FontSizer.getResizedFont(trMessageBox.font, level);
trMessageBox.font = font;
tlMessageBox.font = font;
brMessageBox.font = font;
blMessageBox.font = font;
invalidateImage(); // validImage = false;
}
/**
* Sets the font factor.
*
* @param factor the factor
*/
public void setFontFactor(double factor) {
Font font = FontSizer.getResizedFont(trMessageBox.font, factor);
trMessageBox.font = font;
tlMessageBox.font = font;
brMessageBox.font = font;
blMessageBox.font = font;
invalidateImage(); // validImage = false;
repaint();
}
/**
* Builds the default popup menu for this panel.
*/
protected void buildPopupmenu() {
popupmenu.removeAll();
popupmenu.setEnabled(true);
ActionListener listener = new PopupmenuListener();
if(isZoom()) {
zoomInItem = new JMenuItem(DisplayRes.getString("DisplayPanel.Zoom_in_menu_item")); //$NON-NLS-1$
zoomInItem.addActionListener(listener);
popupmenu.add(zoomInItem);
zoomOutItem = new JMenuItem(DisplayRes.getString("DisplayPanel.Zoom_out_menu_item")); //$NON-NLS-1$
zoomOutItem.addActionListener(listener);
popupmenu.add(zoomOutItem);
}
if(!isFixedScale()) {
autoscaleItem = new JMenuItem(DisplayRes.getString("DrawingFrame.Autoscale_menu_item")); //$NON-NLS-1$
autoscaleItem.addActionListener(listener);
popupmenu.add(autoscaleItem);
scaleItem = new JMenuItem(DisplayRes.getString("DrawingFrame.Scale_menu_item")); //$NON-NLS-1$
scaleItem.addActionListener(listener);
popupmenu.add(scaleItem);
popupmenu.addSeparator();
}
snapshotItem = new JMenuItem(DisplayRes.getString("DisplayPanel.Snapshot_menu_item")); //$NON-NLS-1$
snapshotItem.addActionListener(listener);
popupmenu.add(snapshotItem);
popupmenu.addSeparator();
propertiesItem = new JMenuItem(DisplayRes.getString("DrawingFrame.InspectMenuItem")); //$NON-NLS-1$
propertiesItem.addActionListener(listener);
popupmenu.add(propertiesItem);
}
/**
* Sets the size of the margin during an autoscale operation.
*
* @param _autoscaleMargin
*/
public void setAutoscaleMargin(double _autoscaleMargin) {
if(autoscaleMargin==_autoscaleMargin) {
return;
}
autoscaleMargin = _autoscaleMargin;
invalidateImage(); // validImage = false;
}
/**
* Sets the extra percentage on the X left and right margins during an autoscale operation.
*
* @param _percentage
*/
public void setXMarginPercentage(double _percentage) {
if((xLeftMarginPercentage==_percentage)&&(xRightMarginPercentage==_percentage)) {
return;
}
xLeftMarginPercentage = xRightMarginPercentage = _percentage;
invalidateImage(); // validImage = false;
}
/**
* Sets the extra percentage on the X left and right margins during an autoscale operation.
*
* @param _percentage
*/
public void setXMarginPercentage(double _leftPercentage, double _rightPercentage) {
if((xLeftMarginPercentage==_leftPercentage)&&(xRightMarginPercentage==_rightPercentage)) {
return;
}
xLeftMarginPercentage = _leftPercentage;
xRightMarginPercentage = _rightPercentage;
invalidateImage(); // validImage = false;
}
/**
* Sets the extra percentage on the X left margin during an autoscale operation.
*
* @param _percentage
*/
public void setXLeftMarginPercentage(double _percentage) {
if(xLeftMarginPercentage==_percentage) {
return;
}
xLeftMarginPercentage = _percentage;
invalidateImage(); // validImage = false;
}
/**
* Sets the extra percentage on the X left margin during an autoscale operation.
*
* @param _percentage
*/
public void setXRightMarginPercentage(double _percentage) {
if(xRightMarginPercentage==_percentage) {
return;
}
xRightMarginPercentage = _percentage;
invalidateImage(); // validImage = false;
}
/**
* Sets the extra percentage on the Y top and bottom margin during an autoscale operation.
*
* @param _percentage
*/
public void setYMarginPercentage(double _percentage) {
if((yTopMarginPercentage==_percentage)&&(yBottomMarginPercentage==_percentage)) {
return;
}
yTopMarginPercentage = yBottomMarginPercentage = _percentage;
invalidateImage(); // validImage = false;
}
/**
* Sets the extra percentage on the Y top and bottom margin during an autoscale operation.
*
* @param _percentage
*/
public void setYMarginPercentage(double _bottomPercentage, double _topPercentage) {
if((yBottomMarginPercentage==_bottomPercentage)&&(yTopMarginPercentage==_topPercentage)) {
return;
}
yTopMarginPercentage = _topPercentage;
yBottomMarginPercentage = _bottomPercentage;
invalidateImage(); // validImage = false;
}
/**
* Sets the extra percentage on the Y top margin during an autoscale operation.
*
* @param _percentage
*/
public void setYTopMarginPercentage(double _percentage) {
if(yTopMarginPercentage==_percentage) {
return;
}
yTopMarginPercentage = _percentage;
invalidateImage(); // validImage = false;
}
/**
* Sets the extra percentage on the X left margin during an autoscale operation.
*
* @param _percentage
*/
public void setYBottomMarginPercentage(double _percentage) {
if(yBottomMarginPercentage==_percentage) {
return;
}
yBottomMarginPercentage = _percentage;
invalidateImage(); // validImage = false;
}
/**
* Sets the panel to exclude the gutter from the drawing.
*
* @param clip <code>true<\code> to clip; <code>false<\code> otherwise
*/
public void setClipAtGutter(boolean clip) {
if(clipAtGutter==clip) {
return;
}
clipAtGutter = clip;
invalidateImage(); // validImage = false;
}
/**
* Gets the clip at gutter flag.
*
* @return <code>true<\code> if drawing is clipped at the gutter; <code>false<\code> otherwise
*/
public boolean isClipAtGutter() {
return clipAtGutter;
}
/**
* Sets adjustable gutters. Axes are allowed to adjust the gutter size.
*
* @param fixed <code>true<\code> if gutters remain constant
*/
public void setAdjustableGutter(boolean adjustable) {
if(adjustableGutter==adjustable) {
return;
}
adjustableGutter = adjustable;
invalidateImage(); // validImage = false;
}
/**
* Gets the adjustableGutter flag. Adjustable gutters change as the panel is resized.
*
* @return <code>true<\code> if gutters are adjustable
*/
public boolean isAdjustableGutter() {
return adjustableGutter;
}
/**
* Sets the mouse cursor.
* @param cursor
*/
public void setMouseCursor(Cursor cursor) {
Container c = getTopLevelAncestor();
setCursor(cursor);
if(c!=null) {
c.setCursor(cursor);
}
}
/**
* Checks the image to see if the working image has the correct Dimension.
*
* Checking is done in the event dispatch thread.
*
* @return <code>true <\code> if the offscreen image matches the panel; <code>false <\code> otherwise
*/
protected boolean checkWorkingImage() {
Runnable runImageCheck = new Runnable() {
public void run() {
workingImage();
}
};
if(SwingUtilities.isEventDispatchThread()) {
return workingImage();
}
try {
SwingUtilities.invokeAndWait(runImageCheck);
return true;
} catch(Exception ex) {
OSPLog.finest("Exception in Check Working Image:"+ex.toString()); //$NON-NLS-1$
return false;
}
}
/**
* Checks the image to see if the working image has the correct Dimension.
*
* @return <code>true <\code> if the offscreen image matches the panel; <code>false <\code> otherwise
*/
private boolean workingImage() {
Rectangle r = getBounds();
int width = (int) r.getWidth();
int height = (int) r.getHeight();
if((width<=2)||(height<=2)) {
return false; // panel is too small to draw anything useful
}
if((workingImage==null)||(width!=workingImage.getWidth())||(height!=workingImage.getHeight())) {
this.workingImage = getGraphicsConfiguration().createCompatibleImage(width, height);
invalidateImage(); // validImage = false; // buffer image is not valid
}
if(this.workingImage==null) { // image could not be created
invalidateImage(); // validImage = false; // buffer image is not valid
return false;
}
return true; // the buffered image has been created and is the correct size
}
/**
* Performs the action for the refresh timer by rendering (redrawing) the panel.
*
* @param evt
*/
public void actionPerformed(ActionEvent evt) {
if(!isValidImage()) {
render();
}
}
/**
* Gets the iconified flag from the top level frame.
*
* @return boolean true if frame is iconified; false otherwise
*/
public boolean isIconified() {
Component c = getTopLevelAncestor();
if(c instanceof Frame) {
return(((Frame) c).getExtendedState()&Frame.ICONIFIED)==1;
}
return false;
}
/**
* Paints all drawables onto an offscreen image buffer and copies this image onto the screen.
*
* @return the image buffer
*/
public BufferedImage render() {
if(!isShowing()||isIconified()) {
return offscreenImage; // no need to draw if the frame is not visible
}
if(buffered&&checkWorkingImage()) {
validImage = true; // drawing into the working image will produce a valid image
render(workingImage);
// swap the images
BufferedImage temp = offscreenImage;
offscreenImage = workingImage;
workingImage = temp;
}
// always update a Swing component from the event thread
Runnable doNow = new Runnable() {
public void run() {
paintImmediately(getVisibleRect());
}
};
try {
if(SwingUtilities.isEventDispatchThread()) {
paintImmediately(getVisibleRect());
} else { // paint within the event thread
SwingUtilities.invokeAndWait(doNow);
}
} catch(InvocationTargetException ex1) {}
catch(InterruptedException ex1) {}
if(vidCap!=null) {
if(buffered) { // buffered image exists so use it.
vidCap.addFrame(offscreenImage);
} else { // render the image if the buffer does not exist
// inefficient as the image may be rendered twice during every animation step
if(vidCap.isRecording()) {
vidCap.addFrame(render());
}
}
}
return offscreenImage;
}
/**
* Paints all drawables onto an image.
*
* @param image
* @return the image buffer
*/
public BufferedImage render(BufferedImage image) {
Graphics osg = image.getGraphics();
imageRatio =((float) getWidth()<=0)?1: image.getWidth()/(float) getWidth(); // ratio of image to panel width
if(osg!=null) {
paintEverything(osg);
if(image==workingImage) {
zoomBox.paint(osg); // paint the zoom
}
Rectangle viewRect = this.viewRect; // reference for thread safety
if(viewRect!=null) {
Rectangle r = new Rectangle(0, 0, image.getWidth(null), image.getHeight(null));
glassPanel.setBounds(r);
glassPanelLayout.checkLayoutRect(glassPanel, r);
glassPanel.render(osg);
glassPanel.setBounds(viewRect);
glassPanelLayout.checkLayoutRect(glassPanel, viewRect);
} else {
glassPanel.render(osg);
}
osg.dispose();
}
imageRatio = 1.00;
return image;
}
public int getWidth() {
return(int) (imageRatio*super.getWidth()); // effective width when rendering images
}
public int getHeight() {
return(int) (imageRatio*super.getHeight()); // effective height when rendering images
}
/**
* Gets the ratio of the drawing image to the panel.
* @return double
*/
public double getImageRatio() {
return imageRatio;
}
/**
* Invalidate the offscreen image so that it is rendered during the next repaint operation if buffering is enabled.
*/
public void invalidateImage() {
validImage = false;
}
/**
* Validate the offscreen image to insure that the render method will execute.
*/
public void validateImage() {
validImage = true;
}
protected boolean isValidImage() {
return validImage;
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
boolean resetBuffered = buffered;
if(g2.getDeviceConfiguration().getDevice().getType()==GraphicsDevice.TYPE_PRINTER) {
buffered = false;
//System.out.println("buffer off");
}
super.paint(g);
buffered = resetBuffered;
}
/**
* Paints this component.
* @param g
*/
public void paintComponent(Graphics g) {
if(OSPRuntime.disableAllDrawing) {
g.setColor(bgColor);
g.fillRect(0, 0, getWidth(), getHeight());
return;
}
viewRect = findViewRect(); // find the clipping rectangle within a scroll pane viewport
if(buffered) { // paint bufferImage onto screen
if(!validImage||(getWidth()!=offscreenImage.getWidth())||(getHeight()!=offscreenImage.getHeight())) {
if((getWidth()!=offscreenImage.getWidth())||(getHeight()!=offscreenImage.getHeight())) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
} else {
g.drawImage(offscreenImage, 0, 0, null); // copy old image to the screen for now
}
refreshTimer.start(); // image is not valid so start refresh timer
} else { // current image is valid and has correct size
g.drawImage(offscreenImage, 0, 0, null); // copy image to the screen
}
} else { // paint directly onto the graphics buffer
validImage = true; // painting everything gives a valid onscreen image
paintEverything(g);
}
zoomBox.paint(g);
// if(enableZoom||zoomMode) { // zoom box is always painted on top
// zoomBox.paint(g);
// }
}
/**
* Gets the clipping rectangle within a scroll pane viewport.
*
* @return the clipping rectangle
*/
protected Rectangle getViewRect() {
return viewRect;
}
/**
* Finds the clipping rectangle if this panel is within a scroll pane viewport.
*/
protected Rectangle findViewRect() {
Rectangle rect = null;
Container c = getParent();
while(c!=null) {
if(c instanceof JViewport) {
rect = ((JViewport) c).getViewRect();
glassPanel.setBounds(rect);
glassPanelLayout.checkLayoutRect(glassPanel, rect);
break;
}
c = c.getParent();
}
return rect;
}
/**
* Computes the size of the gutters. Objects, such as axes, can perform this method
* by implementing the Dimensioned interface.
*/
protected void computeGutters() {
if(dimensionSetter!=null) {
Dimension interiorDimension = dimensionSetter.getInterior(this);
if(interiorDimension!=null) {
squareAspect = false;
leftGutter = rightGutter = Math.max(0, getWidth()-interiorDimension.width)/2;
topGutter = bottomGutter = Math.max(0, getHeight()-interiorDimension.height)/2;
}
}
}
/**
* Paints before the panel iterates through its list of Drawables.
* @param g Graphics
*/
protected void paintFirst(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight()); // fill the component with the background color
g.setColor(Color.black); // restore the default drawing color
}
/**
* Paints after the panel iterates through its list of Drawables.
* @param g Graphics
*/
protected void paintLast(Graphics g) {}
/**
* Paints everything inside this component.
*
* @param g
*/
protected void paintEverything(Graphics g) {
if(RECORD_PAINT_TIMES) {
long time = System.currentTimeMillis();
System.out.println("elapsed time(s)="+((int) (time-currentTime)/1000.0)); //$NON-NLS-1$
currentTime = time;
}
// the following statement has been moved to paintComponent
// viewRect = findViewRect(); // finds the clipping rectangle within a scroll pane viewport
computeGutters(); // last chance to set the gutters
ArrayList<Drawable> tempList = getDrawables(); // holds a clone of the drawable object list
scale(tempList); // sets the world-coordinate scale based on the autoscale values
setPixelScale(); // sets the pixel scale and the world-to-pixel affine transformation matrix
if (!OSPRuntime.isMac()) { //Rendering hint bug in Mac Snow Leopard
if (antialiasTextOn) {
((Graphics2D) g).setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
} else {
((Graphics2D) g).setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
if (antialiasShapeOn) {
((Graphics2D) g).setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
} else {
((Graphics2D) g).setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
}
}
// ready to draw everything
if(!validImage) {
return; // abort drawing
}
paintFirst(g); // PlottingPanel uses this method to paint axes
if(!validImage) {
return; // abort drawing
}
paintDrawableList(g, tempList);
if(!validImage) {
return; // abort drawing
}
paintLast(g); // does nothing yet but can be used to add a legend, etc
if(RECORD_PAINT_TIMES) {
System.out.println("paint time (ms)="+(int) (System.currentTimeMillis()-currentTime)+'\n'); //$NON-NLS-1$
}
}
/**
* Autoscale the x axis using min and max values.
* from measurable objects.
* @param autoscale
*/
public void setAutoscaleX(boolean autoscale) {
if((autoscaleX==autoscale)&&(autoscaleXMax==autoscale)&&(autoscaleXMin==autoscale)) {
return;
}
autoscaleX = autoscaleXMax = autoscaleXMin = autoscale;
invalidateImage(); // validImage = false;
}
/**
* Determines if the x axis autoscale property is true.
* @return <code>true<\code> if autoscaled.
*/
public boolean isAutoscaleX() {
return autoscaleX;
}
/**
* Determines if the horizontal maximum value is autoscaled.
* @return <code>true<\code> if xmax is autoscaled.
*/
public boolean isAutoscaleXMax() {
return autoscaleXMax;
}
/**
* Determines if the horizontal minimum value is autoscaled.
* @return <code>true<\code> if xmin is autoscaled.
*/
public boolean isAutoscaleXMin() {
return autoscaleXMin;
}
/**
* Autoscale the y axis using min and max values.
* from measurable objects.
* @param autoscale
*/
public void setAutoscaleY(boolean autoscale) {
if((autoscaleY==autoscale)&&(autoscaleYMax==autoscale)&&(autoscaleYMin==autoscale)) {
return;
}
autoscaleY = autoscaleYMax = autoscaleYMin = autoscale;
invalidateImage(); // validImage = false;
}
/**
* Determines if the y axis autoscale property is true.
* @return <code>true<\code> if autoscaled.
*/
public boolean isAutoscaleY() {
return autoscaleY;
}
/**
* Determines if the vertical maximum value is autoscaled.
* @return <code>true<\code> if ymax is autoscaled.
*/
public boolean isAutoscaleYMax() {
return autoscaleYMax;
}
/**
* Determines if the vertical minimum value is autoscaled.
* @return <code>true<\code> if ymin is autoscaled.
*/
public boolean isAutoscaleYMin() {
return autoscaleYMin;
}
/**
* Gets the logScaleX value.
*
* @return boolean
*/
public boolean isLogScaleX() {
return logScaleX;
}
/**
* Gets the logScaleY value.
*
* @return boolean
*/
public boolean isLogScaleY() {
return logScaleY;
}
/**
* Moves and resizes this component. The new location of the top-left
* corner is specified by <code>x</code> and <code>y</code>, and the
* new size is specified by <code>width</code> and <code>height</code>.
* @param x The new <i>x</i>-coordinate of this component.
* @param y The new <i>y</i>-coordinate of this component.
* @param width The new <code>width</code> of this component.
* @param height The new <code>height</code> of this
* component.
*/
public void setBounds(int x, int y, int width, int height) {
if((getBounds().x==x)&&(getBounds().y==y)&&(getBounds().width==width)&&(getBounds().height==height)) {
return;
}
super.setBounds(x, y, width, height);
invalidateImage(); // validImage = false;
}
public void setBounds(Rectangle r) {
if(getBounds().equals(r)) {
return;
}
super.setBounds(r);
invalidateImage(); // validImage = false;
}
/**
* Sets the buffered image option.
*
* Buffered panels copy the offscreen image into the panel during a repaint unless the image
* has been invalidated. Use the render() method to draw the image immediately.
*
* @param _buffered
*/
public void setBuffered(boolean _buffered) {
if(buffered==_buffered) {
return;
}
buffered = _buffered;
if(buffered) { // turn off Java buffering because we are doing our own
setDoubleBuffered(false);
} else { // small default image is not used
workingImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
offscreenImage = workingImage;
setDoubleBuffered(true); // use Java's buffer
}
invalidateImage(); // validImage = false;
}
public boolean isBuffered() {
return buffered;
}
/**
* Makes the component visible or invisible.
* Overrides <code>JComponent.setVisible</code>.
*
* @param vis true to make the component visible; false to
* make it invisible
*/
public void setVisible(boolean vis) {
if(this.isVisible()==vis) {
return;
}
super.setVisible(vis);
invalidateImage(); // validImage = false;
}
/**
* Limits the xmin and xmax values during autoscaling so that the mininimum value
* will be no greater than the floor and the maximum value will be no
* smaller than the ceil.
*
* Setting a floor or ceil value to <code>Double.NaN<\code> will disable that limit.
*
* @param floor the xfloor value
* @param ceil the xceil value
*/
public void limitAutoscaleX(double floor, double ceil) {
if(ceil-floor<Float.MIN_VALUE) { // insures that floor and ceiling some separation
floor = 0.9*floor-Float.MIN_VALUE;
ceil = 1.1*ceil+Float.MIN_VALUE;
}
xfloor = floor;
xceil = ceil;
}
/**
* Limits ymin and ymax values during autoscaling so that the mininimum value
* will be no greater than the floor and the maximum value will be no
* smaller than the ceil.
*
* Setting a floor or ceil value to <code>Double.NaN<\code> will disable that limit.
*