How do I add background image in JTextPane?

The example below demonstrate how to create a custom JTextPane component that have a background image.

package org.kodejava.example.swing;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class TextPaneWithBackgroundImage extends JFrame {
    public TextPaneWithBackgroundImage() {

    private void initUI() {
        setSize(200, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        String imageFile = "/tree.jpg";
        CustomTextPane textPane = new CustomTextPane(imageFile);

        JScrollPane scrollPane = new JScrollPane(textPane);
        scrollPane.setPreferredSize(new Dimension(getWidth(), getHeight()));

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TextPaneWithBackgroundImage().setVisible(true);

 * A custom text pane that have a background image. To customize the
 * JTextPane we override the paintComponent(Graphics g) method. We have
 * to draw an image before we call the super class paintComponent method.
class CustomTextPane extends JTextPane {
    private String imageFile;

     * Constructor of custome text pane.
     * @param imageFile image file name for the text pane background.
    CustomTextPane(String imageFile) {
        // To be able to draw the background image the component must
        // not be opaque.
        this.imageFile = imageFile;        

    protected void paintComponent(Graphics g) {
        BufferedImage image = null;
        try {
            // Load an image for the background image of out JTextPane.
            image =;
            g.drawImage(image, 0, 0, (int) getSize().getWidth(),
                    (int) getSize().getHeight(), this);
        } catch (IOException e) {


Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply