1 package fr.ifremer.quadrige3.ui.swing.plaf;
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 javax.swing.plaf.synth.SynthTextFieldUI;
29 import javax.swing.text.JTextComponent;
30 import java.awt.*;
31 import java.awt.event.FocusEvent;
32 import java.awt.event.FocusListener;
33
34
35
36
37
38 public class HintSynthTextFieldUI extends SynthTextFieldUI implements FocusListener {
39
40 private String hint;
41 private boolean hideOnFocus;
42 private Color color;
43
44
45
46
47
48
49 public Color getColor() {
50 return color;
51 }
52
53
54
55
56
57
58 public void setColor(Color color) {
59 this.color = color;
60 repaint();
61 }
62
63 private void repaint() {
64 if (getComponent() != null) {
65 getComponent().repaint();
66 }
67 }
68
69
70
71
72
73
74 public boolean isHideOnFocus() {
75 return hideOnFocus;
76 }
77
78
79
80
81
82
83 public void setHideOnFocus(boolean hideOnFocus) {
84 this.hideOnFocus = hideOnFocus;
85 repaint();
86 }
87
88
89
90
91
92
93 public String getHint() {
94 return hint;
95 }
96
97
98
99
100
101
102 public void setHint(String hint) {
103 this.hint = hint;
104 repaint();
105 }
106
107
108
109
110
111
112 public HintSynthTextFieldUI(String hint) {
113 this(hint, false);
114 }
115
116
117
118
119
120
121
122 public HintSynthTextFieldUI(String hint, boolean hideOnFocus) {
123 this(hint, hideOnFocus, null);
124 }
125
126
127
128
129
130
131
132
133 public HintSynthTextFieldUI(String hint, boolean hideOnFocus, Color color) {
134 this.hint = hint;
135 this.hideOnFocus = hideOnFocus;
136 this.color = color;
137 }
138
139
140 @Override
141 public void installUI(JComponent c) {
142 super.installUI(c);
143 c.setDoubleBuffered(true);
144 }
145
146
147 @Override
148 protected void paintSafely(Graphics g) {
149 super.paintSafely(g);
150 JTextComponent comp = getComponent();
151 if (hint != null && comp.getText().length() == 0 && (!(hideOnFocus && comp.hasFocus()))) {
152 if (color != null) {
153 g.setColor(color);
154 } else {
155 g.setColor(comp.getForeground().brighter().brighter().brighter());
156 }
157 g.setFont(comp.getFont().deriveFont(Font.ITALIC));
158 FontMetrics fm = g.getFontMetrics();
159 Rectangle clip = getVisibleEditorRect();
160 int x = (int) clip.getMinX();
161 int y = (int) (clip.getCenterY() + fm.getHeight() / 2. - fm.getDescent());
162 g.drawString(hint, x, y);
163 }
164 }
165
166
167 @Override
168 public void focusGained(FocusEvent e) {
169 if (hideOnFocus) {
170 repaint();
171 }
172 }
173
174
175 @Override
176 public void focusLost(FocusEvent e) {
177 if (hideOnFocus) {
178 repaint();
179 }
180 }
181
182
183 @Override
184 protected void installListeners() {
185 super.installListeners();
186 getComponent().addFocusListener(this);
187 }
188
189
190 @Override
191 protected void uninstallListeners() {
192 super.uninstallListeners();
193 getComponent().removeFocusListener(this);
194 }
195 }