gpt4 book ai didi

java swing JTextField 设置 PlaceHolder

转载 作者:IT老高 更新时间:2023-10-28 20:56:06 27 4
gpt4 key购买 nike

我创建了一个 JTextField,现在我想在该 JTextField 上设置占位符,但我不知道怎么做?请帮忙。这是我的代码:

JTextField database=new JTextField("Enter Data Base Name");
database.setPreferredSize(database.getPreferredSize());
database.setText("");

最佳答案

试试这个类(class):

package playground;

import java.awt.*;

import javax.swing.*;
import javax.swing.text.Document;

@SuppressWarnings("serial")
public class PlaceholderTextField extends JTextField {

public static void main(final String[] args) {
final PlaceholderTextField tf = new PlaceholderTextField("");
tf.setColumns(20);
tf.setPlaceholder("All your base are belong to us!");
final Font f = tf.getFont();
tf.setFont(new Font(f.getName(), f.getStyle(), 30));
JOptionPane.showMessageDialog(null, tf);
}

private String placeholder;

public PlaceholderTextField() {
}

public PlaceholderTextField(
final Document pDoc,
final String pText,
final int pColumns)
{
super(pDoc, pText, pColumns);
}

public PlaceholderTextField(final int pColumns) {
super(pColumns);
}

public PlaceholderTextField(final String pText) {
super(pText);
}

public PlaceholderTextField(final String pText, final int pColumns) {
super(pText, pColumns);
}

public String getPlaceholder() {
return placeholder;
}

@Override
protected void paintComponent(final Graphics pG) {
super.paintComponent(pG);

if (placeholder == null || placeholder.length() == 0 || getText().length() > 0) {
return;
}

final Graphics2D g = (Graphics2D) pG;
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(getDisabledTextColor());
g.drawString(placeholder, getInsets().left, pG.getFontMetrics()
.getMaxAscent() + getInsets().top);
}

public void setPlaceholder(final String s) {
placeholder = s;
}

}

关于java swing JTextField 设置 PlaceHolder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16213836/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com