我构建了一个扩展JTextField类的类和一个自己的提示函数。
package functions;
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JTextField;
public class TextField extends JTextField {
private String hint;
private Color cForeground;
private Color cHint;
public void setHint(String s) {
hint = s;
cForeground = getForeground();
setText(hint);
cHint = new Color(cForeground.getRed(), cForeground.getGreen(),
cForeground.getBlue(), cForeground.getAlpha() / 2);
addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent arg0) {
if (getText().equals("")) {
setForeground(cHint);
setText(hint);
}
}
@Override
public void focusGained(FocusEvent arg0) {
if (getText().equals(hint)) {
setText("");
setForeground(cForeground);
}
}
});
}
}1)目前,我的提示只有在没有聚焦的时候才会出现。但我希望我的提示在它空的时候是可见的--当它被聚焦的时候也是如此。我玩的是ActionListener而不是FocusListener,但我没搞懂。
2)我想对JPasswordField做同样的事情,但我不想在两个不同的类中编写相同的方法。当一个类扩展JTextField而另一个类扩展JPasswordField时,有没有一种方法可以让我在两个类中指向同一个方法?
3)我决定是否应该通过调用getText()来显示提示,但这在处理密码时并不友好(我不想因为记录密码而受到指责……)。有没有其他方法可以防止这种情况发生?
顺便说一下:我知道TextPrompt,但我想构建一个自己的简单解决方案。
发布于 2014-12-30 23:52:28
据我所知,您希望在HTML中有一个叫做placeholder的东西。然后覆盖paintComponent方法,如下所示:
public class STextField extends JTextField{
public static final Color placeholderColor = new Color(cForeground.getRed(), cForeground.getGreen(), cForeground.getBlue(), cForeground.getAlpha() / 2);
public STextField(String placeholder){
this.placeholder = placeholder;
}
protected void paintComponent(final Graphics pG) {
super.paintComponent(pG);
if(placeholder.length() == 0 || getText().length() > 0)
return;
final Graphics2D g = (Graphics2D) pG;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(placeholderColor);
int offset = 4; // This value depends on height of text field. Probably can be calculated from font size.
g.drawString(placeholder, getInsets().left, pG.getFontMetrics().getMaxAscent() + offset);
}
private String placeholder;
}https://stackoverflow.com/questions/27708131
复制相似问题