Displaying Background Image in Swing Components

This is a wonderful way to add background images to Java swing components. We can you this method to add background images for almost all of the swing components. To add image we have to override paintComponent() method.

Eg 1: Add background image to JTextArea
JTextArea textArea = new JTextArea() {
ImageIcon backImage = new ImageIcon("Resources/Background.jpg");
Image image = backImage.getImage();
{setOpaque(false);}
//Override
public void paintComponent (Graphics g) {
g.drawImage(image, 0, 0, this);
super.paintComponent(g);
}
};


Eg 2: Add background image to JDesktopPane

JDesktopPane textArea = new JDesktopPane() {
ImageIcon backImage = new ImageIcon("Resources/Background.jpg");
Image image = backImage.getImage();
{setOpaque(false);}
//Override
public void paintComponent (Graphics g) {
g.drawImage(image, 0, 0, this);
super.paintComponent(g);
}
};

We can use this method to add background images to any Swing component.
 

Reader Comments

Thank You so Much!!!!! I couldn't find out how to do this anywhere!!!

Indeed, thank you very much!

Indeed, thank you very much!

Is it possible to change the background image once a button is clicked? 'Cause based on the code, the way I see it, it seems impossible.



Tribune to Heros

Tribune to Heros
We will never forget the sacrifices you made to protect our country....

Subscribe


Get Google Toolbar Button

Enter your email address:

Delivered by FeedBurner