Java - 文本字段上的占位符 [英] Java - placeholder on textfield
问题描述
我正在尝试使用Swing创建GUI。我的问题是,我有一个文本字段,但我希望它有一个占位符(如在html中)。我在这里和那里读到它可以通过覆盖textfield的paint()来完成。
I'm trying to create a GUI with Swing. My problem is, I have a textfield, but I want it to have a "placeholder" (like in html). I read here and there that it can be done by overriding the paint() of the textfield.
由于我的代码生成,我发现我需要使用自定义创建代码覆盖生成的代码。
Since my code is generated I found out that I need to use the "Custom Creation Code" to override the code that was generated.
以下是我在自定义创建代码字段中添加的内容
Here is what I have put in the "Custom Creation Code" field
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但是里面什么都没有,也许我需要添加一些功能到某些事件,但我不确定。
For now I see the textField but there is nothing in it, maybe I need to add some function onto some event, but I am not sure.
如果有人能伸出援手,我将不胜感激。
I would be grateful if anyone could lend a hand.
编辑:以下是我想要做的演示: http://davidwalsh.name/demo/ html5-placeholder.php
EDIT : Here is a demo of what I want to do : http://davidwalsh.name/demo/html5-placeholder.php
推荐答案
我在oracle论坛上找到了这个。
I found this on the oracle forums.
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 - 文本字段上的占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!