我正在尝试创建一个带有图像和提示的 JTextField。文本字段的功能是搜索一些书籍的搜索字段。现在,我想走得更远一点。我想给图像一个功能。例如,如果我单击图像,则应清除文本字段中的文本。
为了实现这个实现,我创建了一个新类并使用 JTextField 对其进行了扩展。
这是代码:
public class JSearchTextField extends JTextField implements FocusListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private String textWhenNotFocused;
private Icon icon;
private Insets dummyInsets;
private JTextField dummy;
public JSearchTextField() {
super();
Border border = UIManager.getBorder("TextField.border");
dummy = new JTextField("Suchen...");
this.dummyInsets = border.getBorderInsets(dummy);
icon = new ImageIcon(JSearchTextField.class.getResource("/images/clearsearch.png"));
this.addFocusListener(this);
}
public JSearchTextField(String textWhenNotFocused) {
this();
this.textWhenNotFocused = textWhenNotFocused;
}
public void setIcon(ImageIcon newIcon){
this.icon = newIcon;
}
public String getTextWhenNotFocused() {
return this.textWhenNotFocused;
}
public void setTextWhenNotFocused(String newText) {
this.textWhenNotFocused = newText;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
int textX = 2;
if(!this.hasFocus() && this.getText().equals("")) {
int height = this.getHeight();
Font prev = this.getFont();
Font italic = prev.deriveFont(Font.ITALIC);
Color prevColor = g.getColor();
g.setFont(italic);
g.setColor(UIManager.getColor("textInactiveText"));
int h = g.getFontMetrics().getHeight();
int textBottom = (height - h) / 2 + h - 4;
int x = this.getInsets().left;
Graphics2D g2d = (Graphics2D) g;
RenderingHints hints = g2d.getRenderingHints();
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.drawString(textWhenNotFocused, x, textBottom);
g2d.setRenderingHints(hints);
g.setFont(prev);
g.setColor(prevColor);
} else {
int iconWidth = icon.getIconWidth();
int iconHeight = icon.getIconHeight();
int x = dummy.getWidth() + dummyInsets.right;
textX = x - 420;
int y = (this.getHeight() - iconHeight)/2;
icon.paintIcon(this, g, x, y);
}
setMargin(new Insets(2, textX, 2, 2));
}
@Override
public void focusGained(FocusEvent arg0) {
this.repaint();
}
@Override
public void focusLost(FocusEvent arg0) {
this.repaint();
}
}
这就是我创建字段的地方;
txtSearchBooks = new JSearchTextField("Buch suchen...");
现在回到我的问题。您知道如何为图像提供自动清除文本的功能吗?我试图实现一个 MouseListener 并将“txtSearchBooks”的文本设置为 null,但它没有奏效。
我希望我没有走错方向。
很抱歉这篇文章很长,但我真的很感激能得到一些建议。