Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8965125
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T16:44:45+00:00 2026-06-15T16:44:45+00:00

I am trying to create a JTextField with an image and a hint. The

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T16:44:46+00:00Added an answer on June 15, 2026 at 4:44 pm

    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);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to create a TextField, populate it with some text and get
Trying to create a background-image slideshow and am getting this error... This is the
I'm trying to create a hidden textfield for an iphone specific site, basically I've
I have an application in which i am trying to create autocompletion of jTextField
I am trying to create a 'sort by status' function that shows, for example
Is there a way I can create a JTextArea or JTextField with some JLabels
I'm trying create a bot which automatically likes Facebook posts. Using Mechanize I can
I am trying create a delegate representation of constructor by emitting a Dynamic Method,
Ok so I am trying create a login script, here I am using PHP5
Trying to create a black line in my view to separate text blocks but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.