How to set background image in JTextArea

Here is a very simple and working example on setting background image in JTextArea. It is very easy, when you do override the paintComponent(Graphics) method. You might be already familiar with the drawImage() method of the Graphics class. This actually does the thing. You'll really find it interesting.


import javax.swing.*;
import java.awt.*;
import java.io.*;
import javax.imageio.*;
class TextAreaBackgroundImage extends JFrame
{
private ImageJTextArea jt;
    public TextAreaBackgroundImage()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Background image for JTextArea");
        setSize(400,400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
       
            jt=new ImageJTextArea(new File("E:\\Wallpapers\\steelsea.jpg"));
            add(jt);
    }
   
    public static void main(String args[])
    {
        new TextAreaBackgroundImage();
    }
}
class ImageJTextArea extends JTextArea
{
File image;
    public ImageJTextArea(File image)
    {
        setOpaque(false);
        this.image=image;
    }
   
    public void paintComponent(final Graphics g)
    {
        try
        {
        // Scale the image to fit by specifying width,height
        g.drawImage(new ImageIcon(image.getAbsolutePath()).getImage(),0,0,getWidth(),getHeight(),this);
        super.paintComponent(g);
        }catch(Exception e){}
    }
}

Output of TextAreaBackgroundImage


Explaining the paintComponent(Graphics)

It is better to use paintComponent() than the paint() method. The swing components other than the top level containers usually overrides paintComponent()

An important point that i would like to point out is that while drawing an image, just make use of the ImageIcon class rather than the ImageIO. The ImageIcon being specially designed Swing components is much faster than the original ImageIO.read() function. I've tried it in practical. This class has a getImage() method which will return an Image object. The second and third parameters are x,y respectively. Next one is the width and height of the image (for scaling the image to fit to the JTextArea) and next is the ImageObserver which is the current JTextArea only. The ImageObserver receives notifications about image updates.
Also see setting background image in JFrame


Posted by at on

Tags: Swing Hacks,