单击JTextField中的图标,并清除其内容 [英] Click on icon in a JTextField and clear its content

查看:478
本文介绍了单击JTextField中的图标,并清除其内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个带有图像和提示的JTextField。文本字段的功能是搜索某些书籍的搜索字段。现在,我想再进一步。我想给图像一个函数。例如,如果我点击图片文本字段中的文本应该清除。



为了实现这个实现,我创建了一个新类,并扩展它与JTextField。 p>

这是代码:

  public class JSearchTextField extends JTextField implements FocusListener { 

/ **
*
* /
private static final long serialVersionUID = 1L;
private String textWhenNotFocused;
private图标图标;
private Insets dummyInsets;
private JTextField dummy;

public JSearchTextField(){
super();

边框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,但它没有工作。



我希望我没有走错方向。



对不起,将真正感谢得到一些建议。

解决方案

JTextField JComponent ,这意味着它也是其他组件的容器。您可以使用 add(Component c)方法向其中添加其他组件。 BUT A JTextField 将不显示其添加的组件,除非您向其提供 LayoutManager 。然后它的行为就像一个正常的 JPanel



我做了一个小例子,如何管理你需要的。标签显示在右侧,单击它将清除字段。您也可以使用按钮,而不是标签。



请注意,您不需要创建图像对象从头开始,我可以从文件加载它。我以这种方式创建它,使示例不依赖于其他文件。

  public class TextFieldWithLabel {
public static void main(String [] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField textField = new JTextField(Search ...);
textField.setLayout(new BorderLayout());

//创建虚拟映像...
映像image =新的BufferedImage(25,25,BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0,0,25,25);
graphics.setColor(Color.RED);
graphics.fillRect(2,11,21,3);
graphics.fillRect(11,2,3,21);

JLabel label = new JLabel(new ImageIcon(image));
textField.add(label,BorderLayout.EAST);
label.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
textField.setText();
}
});
frame.add(textField);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}


I am trying to create a JTextField with an image and a hint. The function of the textfield is a search field to search some books. Now, I like to go a little bit further. I would like to give the image a function. For example, if I click on the image the text in the textfield should be cleared.

To achieve this implementation I created a new class and extended it with JTextField.

This is the code:

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

}

And this is where I create the fields;

txtSearchBooks = new JSearchTextField("Buch suchen...");

Now back to my question. Do you have any idea how I can give the image a function where the text will be automatically cleared? I tried to implement a MouseListener and set the text of "txtSearchBooks" to null but it hasn't worked.

I hope I didn't go off in the wrong direction.

Sorry for the long post but I would really appreciate to get some advice.

解决方案

A JTextField is a JComponent, meaning it is also a container for other components. You can use the add(Component c) method to add other components to it. BUT A JTextField won't show its added components unless you provide a LayoutManager to it. Then it behaves just like a normal JPanel.

I made a small example how you can manage what you need. The label is showed to the right, and clicking it will clear the field. You can use a button as well, instead of label.

Please note you don't need to create the Image object from scratch as I do, you can load it from a file. I create it this way so that the example doesn't rely on other files.

public class TextFieldWithLabel {
    public static void main(String[] args) 
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextField textField = new JTextField("Search...");
        textField.setLayout(new BorderLayout());

        //creating dummy image...
        Image image = new BufferedImage(25, 25, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, 25, 25);
        graphics.setColor(Color.RED);
        graphics.fillRect(2, 11, 21, 3);
        graphics.fillRect(11, 2, 3, 21);

        JLabel label = new JLabel(new ImageIcon(image));
        textField.add(label, BorderLayout.EAST);
        label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                textField.setText("");
            }
        });
        frame.add(textField);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

这篇关于单击JTextField中的图标,并清除其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆