1 package fr.ifremer.quadrige3.ui.swing.component.date;
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 import javax.swing.*;
28 import java.awt.*;
29
30
31
32
33 public class FittingPopupFactory extends PopupFactory {
34
35
36 @Override
37 public Popup getPopup(Component owner, Component contents, int x, int y) throws IllegalArgumentException {
38
39 if (owner instanceof JComponent && contents instanceof JComponent) {
40 Point bestLoc = adjustPopupLocationToFitScreen((JComponent) owner, (JComponent) contents, x, y);
41 x = bestLoc.x;
42 y = bestLoc.y;
43 }
44
45 return super.getPopup(owner, contents, x, y);
46 }
47
48
49
50
51
52 private Point adjustPopupLocationToFitScreen(JComponent owner, JComponent content, int xPosition, int yPosition) {
53 Point popupLocation = new Point(xPosition, yPosition);
54
55 if (GraphicsEnvironment.isHeadless()) {
56 return popupLocation;
57 }
58
59
60 Rectangle scrBounds;
61 GraphicsConfiguration gc = getCurrentGraphicsConfiguration(owner, popupLocation);
62 Toolkit toolkit = Toolkit.getDefaultToolkit();
63 if (gc != null) {
64
65 scrBounds = gc.getBounds();
66 } else {
67
68 scrBounds = new Rectangle(toolkit.getScreenSize());
69 }
70
71
72 Dimension popupSize = content.getPreferredSize();
73 long popupRightX = (long) popupLocation.x + (long) popupSize.width;
74 long popupBottomY = (long) popupLocation.y + (long) popupSize.height;
75 int scrWidth = scrBounds.width;
76 int scrHeight = scrBounds.height;
77
78
79 Insets scrInsets = toolkit.getScreenInsets(gc);
80 scrBounds.x += scrInsets.left;
81 scrBounds.y += scrInsets.top;
82 scrWidth -= scrInsets.left + scrInsets.right;
83 scrHeight -= scrInsets.top + scrInsets.bottom;
84
85 int scrRightX = scrBounds.x + scrWidth;
86 int scrBottomY = scrBounds.y + scrHeight;
87
88
89 if (popupRightX > (long) scrRightX) {
90 popupLocation.x = scrRightX - popupSize.width;
91 }
92
93 if (popupBottomY > (long) scrBottomY) {
94 popupLocation.y = scrBottomY - popupSize.height;
95 }
96
97 if (popupLocation.x < scrBounds.x) {
98 popupLocation.x = scrBounds.x;
99 }
100
101 if (popupLocation.y < scrBounds.y) {
102 popupLocation.y = scrBounds.y;
103 }
104
105 return popupLocation;
106 }
107
108
109
110
111
112
113 private GraphicsConfiguration getCurrentGraphicsConfiguration(JComponent owner, Point popupLocation) {
114 GraphicsConfiguration gc = null;
115 GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
116 GraphicsDevice[] gd = ge.getScreenDevices();
117 for (GraphicsDevice aGd : gd) {
118 if (aGd.getType() == GraphicsDevice.TYPE_RASTER_SCREEN) {
119 GraphicsConfiguration dgc = aGd.getDefaultConfiguration();
120 if (dgc.getBounds().contains(popupLocation)) {
121 gc = dgc;
122 break;
123 }
124 }
125 }
126
127 if (gc == null) {
128 owner.getGraphicsConfiguration();
129 }
130 return gc;
131 }
132
133 }