This repository has been archived by the owner on Aug 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGhostText.java
128 lines (110 loc) · 2.82 KB
/
GhostText.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
package auto;
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.JTextComponent;
public class GhostText implements FocusListener, DocumentListener, PropertyChangeListener{
private final JTextComponent textComp;
private boolean isEmpty;
private Color ghostColor;
private Color foregroundColor;
private final String ghostText;
public GhostText(final JTextComponent textComp, String ghostText) {
super();
this.textComp = textComp;
this.ghostText = ghostText;
this.ghostColor = Color.LIGHT_GRAY;
textComp.addFocusListener(this);
registerListeners();
updateState();
if (!this.textComp.hasFocus()) {
focusLost(null);
}
}
public void delete()
{
unregisterListeners();
textComp.removeFocusListener(this);
}
private void registerListeners()
{
textComp.getDocument().addDocumentListener(this);
textComp.addPropertyChangeListener("foreground", this);
}
private void unregisterListeners()
{
textComp.getDocument().removeDocumentListener(this);
textComp.removePropertyChangeListener("foreground", this);
}
public Color getGhostColor()
{
return ghostColor;
}
public void setGhostColor(Color ghostColor)
{
this.ghostColor = ghostColor;
}
private void updateState()
{
isEmpty = textComp.getText().length() == 0;
foregroundColor = textComp.getForeground();
}
@Override
public void focusGained(FocusEvent e)
{
if (isEmpty)
{
unregisterListeners();
try
{
textComp.setText("");
textComp.setForeground(foregroundColor);
}
finally
{
registerListeners();
}
}
}
@Override
public void focusLost(FocusEvent e)
{
if (isEmpty)
{
unregisterListeners();
try
{
textComp.setText(ghostText);
textComp.setForeground(ghostColor);
}
finally
{
registerListeners();
}
}
}
@Override
public void propertyChange(PropertyChangeEvent evt)
{
updateState();
}
@Override
public void changedUpdate(DocumentEvent e)
{
updateState();
}
@Override
public void insertUpdate(DocumentEvent e)
{
updateState();
}
@Override
public void removeUpdate(DocumentEvent e)
{
updateState();
}
}