我正在尝试使用 Swing 创建一个 GUI。我的问题是,我有一个文本字段,但我希望它有一个“占位符”(如在 html 中)。我在这里和那里读到它可以通过覆盖文本字段的 paint() 来完成。
自从我的代码生成后,我发现我需要使用“自定义创建代码”来覆盖生成的代码。
这是我在“自定义创建代码”字段中输入的内容
new javax.swing.JTextField()
{
String test = super.getText();
String hint = "Username";
public void paint(Graphics g)
{
if ( test == null || test.length() < 1 ) {
g.setColor( Color.red );
g.drawString(hint, 0, 0);
}
g.setColor(Color.BLACK);
super.paint(g);
}
}
这会生成以下输出
javax.swing.JTextField username = new javax.swing.JTextField()
{
String test = super.getText();
String hint = "Username";
public void paint(Graphics g)
{
if ( test == null || test.length() < 1 ) {
g.setColor( Color.red );
g.drawString(hint, 0, 0);
}
g.setColor(Color.BLACK);
super.paint(g);
}
};
现在我看到了 textField,但里面什么也没有,也许我需要在某些事件上添加一些功能,但我不确定。
如果有人能伸出援手,我将不胜感激。
编辑:这是我想做的演示:http://davidwalsh.name/demo/html5-placeholder.php
最佳答案
我在 oracle 论坛上找到了这个。
public class TextFieldWithPrompt extends JTextField{
@Override
protected void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
if(getText().isEmpty() && ! (FocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == this)){
Graphics2D g2 = (Graphics2D)g.create();
g2.setBackground(Color.gray);
g2.setFont(getFont().deriveFont(Font.ITALIC));
g2.drawString("zip", 5, 10); //figure out x, y from font's FontMetrics and size of component.
g2.dispose();
}
}
https://forums.oracle.com/forums/thread.jspa?threadID=1349874
关于Java - 文本字段上的占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13033600/