How do I display an image in the background of a Swing component?

John Zukowski

You'll need to subclass the component, make sure it is not opaque, and override the paintComponent() method such that the image is drawn before the superclass' paintComponent() method is called.

import javax.swing.*;
import java.awt.*;

public class BackgroundSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Background Example");
    final ImageIcon imageIcon = new ImageIcon("draft.gif");
    JTextArea textArea = new JTextArea() {
      Image image = imageIcon.getImage();
      Image grayImage = GrayFilter.createDisabledImage(image);
      {setOpaque(false);}  // instance initializer
      public void paintComponent (Graphics g) {
        g.drawImage(grayImage, 0, 0, this);
    JScrollPane scrollPane = new JScrollPane(textArea);
    Container content = frame.getContentPane();
    content.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(250, 250);
About | Sitemap | Contact