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

đŸ™‚

Advertisements
%d bloggers like this: