-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClock.java
955 lines (850 loc) · 32.6 KB
/
Clock.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
import static java.awt.BasicStroke.CAP_BUTT;
import static java.awt.BasicStroke.CAP_ROUND;
import static java.awt.BasicStroke.JOIN_MITER;
import static java.awt.BasicStroke.JOIN_ROUND;
import static java.awt.Color.WHITE;
import static java.awt.Font.BOLD;
import static java.awt.Font.PLAIN;
import static java.awt.RenderingHints.KEY_ANTIALIASING;
import static java.awt.RenderingHints.KEY_STROKE_CONTROL;
import static java.awt.RenderingHints.VALUE_ANTIALIAS_ON;
import static java.awt.RenderingHints.VALUE_STROKE_PURE;
import static java.awt.Toolkit.getDefaultToolkit;
import static java.awt.geom.AffineTransform.getScaleInstance;
import static java.awt.geom.AffineTransform.getTranslateInstance;
import static java.awt.image.AffineTransformOp.TYPE_NEAREST_NEIGHBOR;
import static java.awt.image.BufferedImage.TYPE_INT_RGB;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.round;
import static java.util.Collections.singletonMap;
import static java.util.stream.Collectors.toList;
import static javax.swing.SwingUtilities.invokeAndWait;
import static javax.swing.SwingUtilities.invokeLater;
import java.awt.BasicStroke;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Clock {
//Creator: Stefan Nicolae Teodoropol
//Date: 26.07.2019
private static final int SIZE = 500;
public static void main(String[] args) {
Window window = new Window("Clock", SIZE, SIZE);
window.open();
while(window.isOpen()) {
// Time calculation and conversions
long time = System.currentTimeMillis(); //current GMT time in milliseconds
time = time % 86400000; //strip away all of the milliseconds of previous days
time = time / 1000; // convert milliseconds to secs
time = time + 7200; // add two hours for CET
// time is now in seconds
int sec = (int) time % 60; // modulo 60 to find how many secs to the next minute
int min = ((int) time / 60) % 60; // div by 60 and modulo 60 to find mins
int hour24 = ((int) time / (3600) )% 24; // div by 3600, and mod 24 to find hours
int hour = hour24 % 12;
boolean morning = (hour24 <= 11);
// helpful text, can be ignored
/*
window.setColor(0,0,0);
window.drawString("Time hours: " + hour24, 30, 20);
window.drawString("Time mins: " + min, 30, 30);
window.drawString("Time secs: " + sec, 30, 40);
window.drawString("Time: " + hour24 + ":" + min + ":" + sec + " " + (morning ? "AM" : "PM"), 30, 50);
*/
// draw the clock face
window.setColor(240, 240, 240);
double radius = 2.0*SIZE/5.0;
window.fillCircle(SIZE/2.0, SIZE/2.0, radius);
// draw hour numbers 30 degrees apart (12 * 30° = 360°, full circle)
window.setColor(0,0,0);
for (int i = 1; i <= 12; i++) {
String num = Integer.toString(i);
double degree = 30*i*2*Math.PI/360.0;
double hourx = (SIZE/2.0 + (Math.sin(degree)*(0.95*radius))) - 4;
double houry = (SIZE/2.0 - (Math.cos(degree)*(0.95*radius))) + 4;
window.drawString(num, hourx, houry );
}
double radsec = sec*6*2*Math.PI/360.0;
double radmin = min*6*2*Math.PI/360.0;
double radhour = hour*30*2*Math.PI/360.0;
// draw the clock hands
window.setColor(0,0,0);
window.setStrokeWidth(1);
window.drawLine(SIZE/2.0, SIZE/2.0, SIZE/2.0 + (Math.sin(radsec)*(0.90*radius)), SIZE/2.0 - (Math.cos(radsec)*(0.95*radius)));
window.setStrokeWidth(2);
window.drawLine(SIZE/2.0, SIZE/2.0, SIZE/2.0 + (Math.sin(radmin)*(0.85*radius)), SIZE/2.0 - (Math.cos(radmin)*(0.85*radius)));
window.setStrokeWidth(4);
window.drawLine(SIZE/2.0, SIZE/2.0, SIZE/2.0 + (Math.sin(radhour)*(0.7*radius)), SIZE/2.0 - (Math.cos(radhour)*(0.7*radius)));
// display everything and then fill the canvas with white:
window.refreshAndClear(20);
}
}
//END of code by: Stefan Nicolae Teodoropol
}
class Window {
private static final Set<String> legalKeyTexts = new HashSet<>();
private static final Map<Integer, String> code2text = new HashMap<>();
static {
for(Field field : KeyEvent.class.getFields()) {
String name = field.getName();
if(name.startsWith("VK_")) {
String text = name.substring(3).toLowerCase();
try {
int code = field.getInt(KeyEvent.class);
legalKeyTexts.add(text);
code2text.put(code, text);
} catch(Exception e) {}
}
}
}
private static final int MIN_WIDTH = 200;
private static final int MIN_HEIGHT = 100;
private final JFrame frame;
private final JPanel panel;
private final int pixelScale = (int) round(getDefaultToolkit().getScreenResolution() / 96.0);
private BufferedImage canvas;
private BufferedImage snapshot;
private Color color = new Color(0, 0, 0);
private double strokeWidth = 1;
private boolean roundStroke = false;
private int fontSize = 11;
private boolean bold = false;
private Map<String, BufferedImage> images = new HashMap<>();
private Map<String, BufferedImage> scaledImages = new HashMap<>();
private Object inputLock = new Object();
private Set<Input> pressedInputs = new HashSet<>();
private Set<Input> releasedInputs = new HashSet<>();
private Set<Input> pressedSnapshot = new HashSet<>();
private Set<Input> releasedSnapshot = new HashSet<>();
private volatile double mouseX = 0;
private volatile double mouseY = 0;
private volatile boolean open = false;
private volatile double width;
private volatile double height;
private long lastRefreshTime = 0;
/**
* Create a new window with the specified title, width, and height.
*/
public Window(String title, int width, int height) {
this.width = width;
this.height = height;
frame = new JFrame();
frame.setTitle(title);
frame.setResizable(false);
frame.setMinimumSize(new Dimension((int) toNative(MIN_WIDTH), (int) toNative(MIN_HEIGHT)));
panel = new JPanel() {
public void paintComponent(Graphics g) {
synchronized(Window.this) {
g.drawImage(snapshot, 0, 0, null);
}
}
};
Dimension size = new Dimension((int) toNative(width), (int) toNative(height));
panel.setSize(size);
panel.setPreferredSize(size);
panel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
synchronized(inputLock) {
pressedInputs.add(new MouseInput(e));
}
}
@Override
public void mouseReleased(MouseEvent e) {
MouseInput input = new MouseInput(e);
synchronized(inputLock) {
pressedInputs.remove(input);
releasedInputs.add(input);
}
}
});
panel.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
mouseX = toUser(e.getX());
mouseY = toUser(e.getY());
}
@Override
public void mouseDragged(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if(x >= 0 && x < width && y >= 0 && y < height) {
mouseX = toUser(x);
mouseY = toUser(y);
}
}
});
panel.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
Window.this.width = toUser(panel.getWidth());
Window.this.height = toUser(panel.getHeight());
}
});
frame.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
synchronized(inputLock) {
pressedInputs.add(new KeyInput(e));
}
}
@Override
public void keyReleased(KeyEvent e) {
KeyInput input = new KeyInput(e);
synchronized(inputLock) {
pressedInputs.remove(input);
releasedInputs.add(input);
}
}
});
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
open = false;
}
});
frame.setContentPane(panel);
canvas = newCanvas();
snapshot = newCanvas();
Thread main = Thread.currentThread();
new Thread(() -> {
while(true) {
try {
main.join();
break;
} catch (InterruptedException e) {}
}
invokeLater(() -> frame.dispose());
}).start();
}
/**
* Opens the window and displays the current content of the canvas.
*/
public void open() {
canvas.copyData(snapshot.getRaster());
open = true;
run(() -> {
frame.pack();
frame.setLocationRelativeTo(null); // center
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.toFront();
frame.setAlwaysOnTop(false);
});
}
/**
* Closes the window.
*/
public void close() {
run(() -> frame.setVisible(false));
}
/**
* Returns <code>true</code> if the window is currently open, <code>false</code>
* otherwise. Note that the window can be closed either by the programmer
* (by calling {@link #close()}) or by the user.
*/
public boolean isOpen() {
return open;
}
/**
* This method returns only once the window is closed by the user (or if it
* was not open in the first place). More precisely, this method returns, as
* soon as {@link #isOpen()} returns <code>true</code>.
*/
public void waitUntilClosed() {
while(isOpen())
try {
Thread.sleep((long) 50);
} catch (InterruptedException e) {}
}
/**
* Displays the current content of the canvas. Use this method in a loop,
* together with {@link #isOpen()}:
*
* <pre>
* while(window.isOpen()) {
* ...
* window.refresh();
* }
* </pre>
*
* In addition, this method also clears the <code>was...Pressed()</code> and
* <code>was...Clicked()</code> input events.
* <p>
* Note that this method is equivalent to {@link #refresh(int) refresh(0)}.
*
* @see #refreshAndClear()
*/
public void refresh() {
refresh(0);
}
/**
* Displays the current content of the canvas. To achieve a constant time
* interval between iterations, this method does not return until the given
* <code>waitTime</code> (in milliseconds) has elapsed since the last refresh.
* For example, to get a frame rate of 50 frames per second, use a
* <code>waitTime</code> of <code>1000 / 50 = 20</code> milliseconds:
* <pre>
* while(window.isOpen()) {
* ...
* window.refresh(20);
* }
* </pre>
*
* In addition, this method also clears the <code>was...Pressed()</code> and
* <code>was...Clicked()</code> input events.
*
* @see #refreshAndClear(int)
*/
public void refresh(int waitTime) {
refresh(waitTime, false);
}
/**
* Displays the current content of the canvas, clears the
* <code>was...Pressed()</code> and <code>was...Clicked()</code> input events,
* and then clears the canvas for the next iteration. Call this method instead
* of {@link #refresh()} if every frame is drawn from scratch.
* <p>
* Note that this method is equivalent to {@link #refreshAndClear(int)
* refreshAndClear(0)}.
*/
public void refreshAndClear() {
refreshAndClear(0);
}
/**
* Displays the current content of the canvas, clears the
* <code>was...Pressed()</code> and <code>was...Clicked()</code> input events,
* and then clears the canvas for the next iteration. Call this method instead
* of {@link #refresh(int)} if every frame is drawn from scratch. To achieve a
* constant time interval between iterations, this method does not return until
* the given <code>waitTime</code> (in milliseconds) has elapsed since the last
* refresh.
*/
public void refreshAndClear(int waitTime) {
refresh(waitTime, true);
}
private void refresh(int waitTime, boolean clear) {
if(clear) {
synchronized(this) {
BufferedImage newCanvas = snapshot;
snapshot = canvas;
canvas = newCanvas;
}
clear(canvas);
} else {
synchronized(this) {
Graphics g = snapshot.getGraphics();
g.drawImage(canvas, 0, 0, null);
g.dispose();
}
}
while(true) {
long sleepTime = (waitTime - (System.currentTimeMillis() - lastRefreshTime)) / 2;
try {
if(sleepTime > 1)
Thread.sleep(sleepTime);
else
break;
} catch (InterruptedException e) {}
}
lastRefreshTime = System.currentTimeMillis();
frame.repaint();
pressedSnapshot.clear();
releasedSnapshot.clear();
synchronized(inputLock) {
pressedSnapshot.addAll(pressedInputs);
releasedSnapshot.addAll(releasedInputs);
releasedInputs.clear();
}
}
private static void clear(BufferedImage image) {
int[] data = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
for(int i = 0; i < data.length; i++)
data[i] = 0xFFFFFFFF;
}
private BufferedImage newCanvas() {
Dimension size = getDefaultToolkit().getScreenSize();
BufferedImage canvas = new BufferedImage(size.width, size.height, TYPE_INT_RGB);
Graphics g = canvas.getGraphics();
g.setColor(WHITE);
g.fillRect(0, 0, size.width, size.height);
g.dispose();
return canvas;
}
/**
* If <code>resizable</code> is <code>true</code>, this window can be
* resized by the user. By default, windows are non-resizable.
* <p>
* For resizable windows, use {@link #getWidth()} and {@link #getHeight()}
* to get the current window size.
*/
public void setResizable(boolean resizable) {
run(() -> frame.setResizable(resizable));
}
/**
* Returns the current window width.
*/
public double getWidth() {
return width;
}
/**
* Returns the current window height (excluding any title bar added
* by the operating system).
*/
public double getHeight() {
return height;
}
/*
* Painting
*/
/**
* Sets the color for the subsequent drawing operations. The three
* parameters represent the red, green, and blue channel and are
* expected to be in the 0–255 range. Values outside this
* range will be clamped. The default color is black (0, 0, 0).
*/
public void setColor(int red, int green, int blue) {
color = new Color(red, green, blue);
}
/**
* Sets the color for the subsequent drawing operations, using a
* {@link Color} object. The default color is black (0, 0, 0).
*/
public void setColor(Color color) {
this.color = color;
}
/**
* Returns the current drawing color.
*/
public Color getColor() {
return color;
}
/**
* Sets the stroke width for subsequent <code>draw...()</code>
* operations, in pixels. The default stroke width is 1 pixel.
*/
public void setStrokeWidth(double strokeWidth) {
this.strokeWidth = strokeWidth;
}
/**
* Returns the current stroke width (in pixels).
*/
public double getStrokeWidth() {
return strokeWidth;
}
/**
* If <code>roundStroke</code> is <code>true</code>, subsequent
* <code>draw...()</code> operations will use round stroke caps
* and joins instead of flat caps and miter joins.
*/
public void setRoundStroke(boolean roundStroke) {
this.roundStroke = roundStroke;
}
/**
* Sets the font size for subsequent {@link #drawString(String, int, int)}
* operations, in points. The default font size is 11 points.
*/
public void setFontSize(int fontSize) {
this.fontSize = fontSize;
}
/**
* Returns the current font size, in points.
*/
public int getFontSize() {
return fontSize;
}
/**
* If <code>bold</code> is <code>true</code>, subsequent
* {@link #drawString(String, int, int)} operations will use a bold
* font.
*/
public void setBold(boolean bold) {
this.bold = bold;
}
/**
* Draws the outline of a rectangle with the upper-left corner at
* (<code>x</code>, <code>y</code>) and the given <code>width</code>
* and <code>height</code>. The current {@linkplain #getColor() color}
* and {@linkplain #getStrokeWidth() stroke width} are used.
*/
public void drawRect(double x, double y, double width, double height) {
withGraphics(g -> g.draw(new Rectangle2D.Double(toNative(x), toNative(y), toNative(width), toNative(height))));
}
/**
* Draws the outline of an oval with a rectangular bounding box that has
* the upper-left corner at (<code>x</code>, <code>y</code>) and the given
* <code>width</code> and <code>height</code>. The current
* {@linkplain #getColor() color} and {@linkplain #getStrokeWidth() stroke width}
* are used.
*/
public void drawOval(double x, double y, double width, double height) {
withGraphics(g -> g.draw(new Ellipse2D.Double(toNative(x), toNative(y), toNative(width), toNative(height))));
}
/**
* Draws the outline of a circle with the center at (<code>x</code>, <code>y</code>)
* and the given <code>radius</code>. The current {@linkplain #getColor() color}
* and {@linkplain #getStrokeWidth() stroke width} are used.
*/
public void drawCircle(double centerX, double centerY, double radius) {
drawOval(centerX - radius, centerY - radius, radius * 2, radius * 2);
}
/**
* Draws a line from (<code>x1</code>, <code>y1</code>) to (<code>x2</code>, <code>y2</code>).
* The current {@linkplain #getColor() color} and {@linkplain #getStrokeWidth() stroke width}
* are used.
*/
public void drawLine(double x1, double y1, double x2, double y2) {
withGraphics(g -> g.draw(new Line2D.Double(toNative(x1), toNative(y1), toNative(x2), toNative(y2))));
}
/**
* Draw the given string with the current {@linkplain #getColor() color}.
* The baseline of the first character is at position (<code>x</code>, <code>y</code>).
*/
public void drawString(String string, double x, double y) {
withGraphics(g -> g.drawString(string, (float) toNative(x), (float) toNative(y)));
}
/**
* Draws the image found at the given <code>path</code> with the upper-left
* corner at position (<code>x</code>, <code>y</code>).
* <p>
* For homework submissions, put all images in the project directory and refer
* to them using relative paths (i.e., not starting with "C:\" or "/"). For
* example, an image called "image.jpg" in the project folder can be referred to
* simply using the path "image.jpg". If you put the image into a subfolder,
* e.g., "images", refer to it using the path "images/image.jpg". Also, make
* sure to commit all required images to the SVN repository.
*/
public void drawImage(String path, double x, double y) {
ensureLoaded(path);
withGraphics(g -> g.drawImage(scaledImages.get(path), getTranslateInstance(toNative(x), toNative(y)), null));
}
/**
* Draws the image found at the given path with the center at position
* (<code>x</code>, <code>y</code>).
* <p>
* Also, see {@link #drawImage(String, double, double)}.
*/
public void drawImageCentered(String path, double x, double y) {
ensureLoaded(path);
BufferedImage img = scaledImages.get(path);
withGraphics(g -> g.drawImage(img, getTranslateInstance(toNative(x) - img.getWidth()/2, toNative(y) - img.getHeight()/2), null));
}
/**
* Draws the image found at the given <code>path</code> with the upper-left
* corner at position (<code>x</code>, <code>y</code>) and scales it by the
* given <code>scale</code>. For example, a scale of 2.0 doubles the size of the
* image.
* <p>
* Also, see {@link #drawImage(String, double, double)}.
*/
public void drawImage(String path, double x, double y, double scale) {
drawImage(path, x, y, scale, 0);
}
/**
* Draws the image found at the given path with the center at position
* (<code>x</code>, <code>y</code>) and scales it by the given <code>scale</code>.
* For example, a scale of 2.0 doubles the size of the image.
* <p>
* Also, see {@link #drawImage(String, double, double)}.
*/
public void drawImageCentered(String path, double x, double y, double scale) {
drawImageCentered(path, x, y, scale, 0);
}
private void drawImage(String path, double x, double y, double scale, double angle) {
ensureLoaded(path);
BufferedImage image = images.get(path);
AffineTransform transform = new AffineTransform();
transform.translate(toNative(x), toNative(y));
transform.scale(scale * pixelScale, scale * pixelScale);
transform.rotate(angle, image.getWidth()/2, image.getHeight()/2);
withGraphics(g -> g.drawImage(image, transform, null));
}
/**
* Draws the image found at the given path with the center at position
* (<code>x</code>, <code>y</code>), scales it by the given <code>scale</code>
* and rotates it by the given <code>angle</code>, in radians (0–2×{@linkplain Math#PI π}).
* <p>
* Also, see {@link #drawImage(String, double, double)}.
*/
public void drawImageCentered(String path, double x, double y, double scale, double angle) {
ensureLoaded(path);
BufferedImage image = images.get(path);
AffineTransform transform = new AffineTransform();
transform.translate(toNative(x) - image.getWidth()/2 * pixelScale*scale,
toNative(y) - image.getHeight()/2 * pixelScale*scale);
transform.scale(scale * pixelScale, scale * pixelScale);
transform.rotate(angle, image.getWidth()/2, image.getHeight()/2);
withGraphics(g -> g.drawImage(image, transform, null));
}
private BufferedImage ensureLoaded(String imagePath) throws Error {
if(!images.containsKey(imagePath)) {
try {
BufferedImage image = ImageIO.read(new File(imagePath));
if(image == null)
throw new Error("could not load image \"" + imagePath + "\"");
images.put(imagePath, image);
BufferedImage scaled;
if(pixelScale == 1)
scaled = image;
else {
AffineTransformOp op = new AffineTransformOp(getScaleInstance(pixelScale, pixelScale), TYPE_NEAREST_NEIGHBOR);
scaled = op.filter(image, null);
}
scaledImages.put(imagePath, scaled);
} catch (IOException e) {
throw new Error("could not load image \"" + imagePath + "\"", e);
}
}
return images.get(imagePath);
}
/**
* Fills a rectangle that has the upper-left corner at (<code>x</code>,
* <code>y</code>) and the given <code>width</code> and <code>height</code> with
* the current {@linkplain #getColor() color}.
*/
public void fillRect(double x, double y, double width, double height) {
withGraphics(g -> g.fill(new Rectangle2D.Double(toNative(x), toNative(y), toNative(width), toNative(height))));
}
/**
* Fills an oval with the current {@linkplain #getColor() color}. The oval has a
* rectangular bounding box with the upper-left corner at (<code>x</code>,
* <code>y</code>) and the given <code>width</code> and <code>height</code>
*/
public void fillOval(double x, double y, double width, double height) {
withGraphics(g -> g.fill(new Ellipse2D.Double(toNative(x), toNative(y), toNative(width), toNative(height))));
}
/**
* Fills a circle that has the center at (<code>x</code>, <code>y</code>) and
* the given <code>radius</code> with the current {@linkplain #getColor()
* color}.
*/
public void fillCircle(double centerX, double centerY, double radius) {
fillOval(centerX - radius, centerY - radius, radius * 2, radius * 2);
}
private void withGraphics(Consumer<Graphics2D> command) {
Graphics2D g = canvas.createGraphics();
g.addRenderingHints(singletonMap(KEY_STROKE_CONTROL, VALUE_STROKE_PURE));
g.addRenderingHints(singletonMap(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON));
g.setColor(new java.awt.Color(color.r, color.g, color.b));
g.setStroke(new BasicStroke((float) (toNative(strokeWidth)),
roundStroke ? CAP_ROUND : CAP_BUTT,
roundStroke ? JOIN_ROUND : JOIN_MITER));
g.setFont(g.getFont().deriveFont(bold ? BOLD : PLAIN, (float) toNative(fontSize)));
command.accept(g);
g.dispose();
}
/*
* Input
*/
public List<String> getPressedKeys() {
return pressedSnapshot.stream()
.filter(i -> i instanceof KeyInput)
.map(i -> ((KeyInput) i).key)
.collect(toList());
}
public List<String> getTypedKeys() {
return releasedSnapshot.stream()
.filter(i -> i instanceof KeyInput)
.map(i -> ((KeyInput) i).key)
.collect(toList());
}
/**
* Returns whether the key specified by the given <code>keyText</code> is
* currently pressed. Use {@link #getPressedKeys()} to find out the names
* for your keys.
*/
public boolean isKeyPressed(String keyName) {
return pressedSnapshot.contains(new KeyInput(keyName));
}
/**
* Returns whether the key specified by the given <code>keyText</code> was
* just typed (released). Use {@link #getPressedKeys()} to find out the names
* for your keys.
*/
public boolean wasKeyTyped(String keyName) {
return releasedSnapshot.contains(new KeyInput(keyName));
}
/**
* Returns whether the left mouse button is currently pressed. Use
* {@link #getMouseX()} and {@link #getMouseY()} to get the current mouse
* position.
*
* @see #isRightMouseButtonPressed()
*/
public boolean isLeftMouseButtonPressed() {
return pressedSnapshot.contains(new MouseInput(true));
}
/**
* Returns whether the right mouse button is currently pressed. Use
* {@link #getMouseX()} and {@link #getMouseY()} to get the current mouse
* position.
*
* @see #isLeftMouseButtonPressed()
*/
public boolean isRightMouseButtonPressed() {
return pressedSnapshot.contains(new MouseInput(false));
}
/**
* Returns whether the left mouse button was just clicked (released). Use
* {@link #getMouseX()} and {@link #getMouseY()} to get the current mouse
* position.
*
* @see #isRightMouseButtonClicked()
*/
public boolean wasLeftMouseButtonClicked() {
return releasedSnapshot.contains(new MouseInput(true));
}
/**
* Returns whether the right mouse button was just clicked (released). Use
* {@link #getMouseX()} and {@link #getMouseY()} to get the current mouse
* position.
*
* @see #isLeftMouseButtonClicked()
*/
public boolean wasRightMouseButtonClicked() {
return releasedSnapshot.contains(new MouseInput(false));
}
/**
* Returns the x coordinate of the current mouse position within the
* window.
*
* @see #getMouseY()
*/
public double getMouseX() {
return mouseX;
}
/**
* Returns the y coordinate of the current mouse position within the
* window.
*
* @see #getMouseX()
*/
public double getMouseY() {
return mouseY;
}
private void run(Runnable run) {
try {
invokeAndWait(run);
} catch (InvocationTargetException e) {
throw new Error(e);
} catch (InterruptedException e) {}
}
/** Converts the given number of "user space" pixels to native pixels (for high-DPI displays). */
private double toNative(double pixels) {
return pixels * pixelScale;
}
/** Converts the given number of native pixels to "user space" pixels (for high-DPI displays). */
private double toUser(double pixels) {
return pixels / pixelScale;
}
private static class Input {}
private static class KeyInput extends Input {
String key;
KeyInput(KeyEvent e) {
this(code2text.get(e.getKeyCode()));
}
KeyInput(String keyText) {
if(!legalKeyTexts.contains(keyText.toLowerCase()))
throw new IllegalArgumentException("key \"" + keyText + "\" does not exist");
this.key = keyText.toLowerCase();
}
public int hashCode() {
return 31 + key.hashCode();
}
public boolean equals(Object obj) {
return this == obj || obj != null && obj instanceof KeyInput && key.equals(((KeyInput) obj).key);
}
}
private static class MouseInput extends Input {
boolean left;
MouseInput(MouseEvent e) {
this(SwingUtilities.isLeftMouseButton(e));
}
MouseInput(boolean left) {
this.left = left;
}
@Override
public int hashCode() {
return 31 + (left ? 1231 : 1237);
}
@Override
public boolean equals(Object obj) {
return this == obj || obj != null && obj instanceof MouseInput && left == ((MouseInput) obj).left;
}
}
}
/**
* A class to represent colors.
*/
final class Color {
public final int r, g, b;
/**
* Creates a new color. The three parameters represent the red, green, and blue
* channel and are expected to be in the 0–255 range. Values outside this
* range will be clamped.
*/
public Color(int r, int g, int b) {
this.r = clamp(r);
this.g = clamp(g);
this.b = clamp(b);
}
private static int clamp(int raw) {
return max(0, min(255, raw));
}
/**
* Returns an integer representation of this color.
*/
public int toRgbInt() {
return r << 16 | g << 8 | b;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + r;
result = prime * result + g;
result = prime * result + b;
return result;
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
Color other = (Color) obj;
return r == other.r && g == other.g && b == other.b;
}
}