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);
        super.paintComponent(g);
      }
    };
    JScrollPane scrollPane = new JScrollPane(textArea);
    Container content = frame.getContentPane();
    content.add(scrollPane, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(3);
    frame.setSize(250, 250);
    frame.setVisible(true);
  }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact