带有输入提示的 Java JTextField
2022-08-31 22:20:14
我想在我的javax.swing.JTextField
中添加一个提示值。它应该看起来像 火狐 渲染 .这将创建一个编辑字段,背景中带有文本“bla”。如果文本框具有焦点,则标题文本将消失,并且当用户离开没有文本的编辑框时,标题文本将重新出现。<input type="text" title="bla">
是否有(自由)摆动组件可以执行此类操作?
我想在我的javax.swing.JTextField
中添加一个提示值。它应该看起来像 火狐 渲染 .这将创建一个编辑字段,背景中带有文本“bla”。如果文本框具有焦点,则标题文本将消失,并且当用户离开没有文本的编辑框时,标题文本将重新出现。<input type="text" title="bla">
是否有(自由)摆动组件可以执行此类操作?
您可以创建自己的:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
final JTextField textFieldA = new HintTextField("A hint here");
final JTextField textFieldB = new HintTextField("Another hint here");
frame.add(textFieldA, BorderLayout.NORTH);
frame.add(textFieldB, BorderLayout.CENTER);
JButton btnGetText = new JButton("Get text");
btnGetText.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String message = String.format("textFieldA='%s', textFieldB='%s'",
textFieldA.getText(), textFieldB.getText());
JOptionPane.showMessageDialog(frame, message);
}
});
frame.add(btnGetText, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
}
class HintTextField extends JTextField implements FocusListener {
private final String hint;
private boolean showingHint;
public HintTextField(final String hint) {
super(hint);
this.hint = hint;
this.showingHint = true;
super.addFocusListener(this);
}
@Override
public void focusGained(FocusEvent e) {
if(this.getText().isEmpty()) {
super.setText("");
showingHint = false;
}
}
@Override
public void focusLost(FocusEvent e) {
if(this.getText().isEmpty()) {
super.setText(hint);
showingHint = true;
}
}
@Override
public String getText() {
return showingHint ? "" : super.getText();
}
}
如果您仍在使用 Java 1.5,请将 .this.getText().isEmpty()
this.getText().length() == 0
这里有一个简单的方法,在任何L&F中看起来都很好:
public class HintTextField extends JTextField {
public HintTextField(String hint) {
_hint = hint;
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (getText().length() == 0) {
int h = getHeight();
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
Insets ins = getInsets();
FontMetrics fm = g.getFontMetrics();
int c0 = getBackground().getRGB();
int c1 = getForeground().getRGB();
int m = 0xfefefefe;
int c2 = ((c0 & m) >>> 1) + ((c1 & m) >>> 1);
g.setColor(new Color(c2, true));
g.drawString(_hint, ins.left, h / 2 + fm.getAscent() / 2 - 2);
}
}
private final String _hint;
}