gpt4 book ai didi

java - jTextField 中的 Fantom 文本。如何?

转载 作者:行者123 更新时间:2023-12-01 16:48:52 25 4
gpt4 key购买 nike

我们遇到一些流行网站的登录屏幕,其中用户名文本框中写有淡灰色的用户名。我想知道这可以在java swings中实现吗?

I have theories, implementing by mouseEvents. Couldn't figure out how to to.

最佳答案

一种方法:

  • 创建一个类,在启动时提供 JTextField 虚拟文本
  • 将文本的前景设置为浅色
  • 使用 FocusListener,它将选择所有虚拟文本并将前景更改为默认颜色(设置为 null)。

例如:

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class FantomTextFieldTest extends JPanel {
FantomTextField fantomTextField = new FantomTextField("Fantom Text");

public FantomTextFieldTest() {
setLayout(new GridLayout(1, 0, 5, 0));
add(new JTextField(20));
add(fantomTextField.getTextField());
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}

private static void createAndShowGui() {
FantomTextFieldTest mainPanel = new FantomTextFieldTest();
JFrame frame = new JFrame("FantomTextFieldTest");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}

class FantomTextField {
private static final Color FANTOM_FG = new Color(150, 150, 150, 150);
private JTextField textField;
private String fantomText;
private boolean showFantomText = true;

public FantomTextField(String fantomText) {
this.fantomText = fantomText;
textField = new JTextField();
textField.setText(fantomText);
textField.setForeground(FANTOM_FG);
textField.addFocusListener(new FtfFocusListener());
}

public FantomTextField(String fantomText, int columns) {
this(fantomText);
textField.setColumns(columns);
}

public JTextField getTextField() {
return textField;
}

public String getFantomText() {
return fantomText;
}

public void setFantomText(String fantomText) {
this.fantomText = fantomText;
textField.setText(fantomText);
textField.setForeground(FANTOM_FG);
showFantomText = true;
}

private class FtfFocusListener extends FocusAdapter {
@Override
public void focusGained(FocusEvent e) {
if (showFantomText) {
textField.selectAll();
textField.setForeground(null);
showFantomText = false;
}
}
}
}

关于java - jTextField 中的 Fantom 文本。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44615390/

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