Java输出语句占位符,Java - 文本字段上的占位符

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);

}

}

This generates the following output

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);

}

};

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.

解决方案

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值