tags:

views:

551

answers:

4

Hello, I have created one GUI using Swing of Java. I have to now set one sample.jpeg image as a background to the frame on which I have put my components.How to do that ?

+3  A: 

There is no concept of a "background image" in a JPanel, so one would have to write their own way to implement such a feature.

One way to achieve this would be to override the paintComponent method to draw a background image on each time the JPanel is refreshed.

For example, one would subclass a JPanel, and add a field to hold the background image, and override the paintComponent method:

public class JPanelWithBackground extends JPanel {

  private Image backgroundImage;

  // Some code to initialize the background image.
  // Here, we use the constructor to load the image. This
  // can vary depending on the use case of the panel.
  public JPanelWithBackground(String fileName) throws IOException {
    backgroundImage = ImageIO.read(new File(fileName));
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Draw the background image.
    g.drawImage(backgroundImage, 0, 0, null);
  }
}

(Above code has not been tested.)

The following code could be used to add the JPanelWithBackground into a JFrame:

JFrame f = new JFrame();
f.getContentPane().add(new JPanelWithBackground("sample.jpeg"));

In this example, the ImageIO.read(File) method was used to read in the external JPEG file.

coobird
Thanks Coobird
om
+1  A: 

You can either make a subclass of the component

http://www.jguru.com/faq/view.jsp?EID=9691

Or fiddle with wrappers

http://www.java-tips.org/java-se-tips/javax.swing/wrap-a-swing-jcomponent-in-a-background-image.html

UberAlex
Thanks UberAlex
om
A: 

The Background Panel entry shows a couple of different ways depending on your requirements.

camickr
Thanks camickr
om
A: 

Here is another quick approach without using additional panel.

JFrame f = new JFrame("stackoverflow") { 
  private Image backgroundImage = ImageIO.read(new File("background.jpg"));
  public void paint( Graphics g ) { 
    super.paint(g);
    g.drawImage(backgroundImage, 0, 0, null);
  }
};
xrath