JTextField with image inside it

The final output will look like following:

textBox_with_image

I applied same logic as one will do with css if it was meant for website. Just 2 simple steps:

  1. Draw the image as background in text box.
  2. Set margin of image width for text inside text box.

For the first step one have to override painComponent method of JTextField as follow:

final BufferedImage image = ImageIO.read(Test.class.getClassLoader().getResource("img/user.png"));
JTextField textField = new JTextField() {
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        int centerPoint = (getHeight() - image.getHeight())/2;
        g.drawImage(image, 0, centerPoint, this);
    }
};

And for the second step:

textField.setMargin(new Insets(0, image.getWidth(), 0, 0));

That’s it. When you use it you will see a text box with image at it’s left as shown in above image.

If you are using custom border for text field and and if is overlapping the image then don’t panic just shift your image slightly as follows:

Get textField’s border inset from the left:

final int borderInset = border.getBorderInsets(new JTextField()).left; // here border is the object indicating Border of JTextField.

Now add it to ‘x’ point in drawImage and serMargin method:

//inside first step
g.drawImage(image, borderInset, centerPoint, this);

//second step
textField.setMargin(new Insets(0, borderInset + image.getWidth(), 0, 0));

As final point don’t forget to increase text field’s height according to your image. If you don’t want to bother to calculate then following line might be helpful to you:

textField.setPreferredSize(new Dimension(textField.getWidth(), image.getHeight() + 10));

:)

About these ads

About harryjoy
A passionate self-taught software developer. Currently working as Software Engineer in an IT company located in INDIA.

4 Responses to JTextField with image inside it

  1. Pingback: JavaPins

  2. Pingback: Java desktop links of the week, July 30 | Jonathan Giles

  3. Rohit says:

    Can you plz , give us whole code for this , How can execute this actually i m new in java..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 69 other followers

%d bloggers like this: