Tuesday, November 2, 2010

Add an image background to a JFrame

This semester we started studying GUI and the first thing I wanted to know is how to make these dull JFrame windows look better. Here is a simple class that I created to change the JFrame's background to any image. It's a good idea to make it a package since you can use it with any JFrame.

/**
 * A panel with the background image on it.
 * @author Yves
 */
class Background extends JPanel {

    private Image img;

    public Background(String path) {

        this(new ImageIcon(path).getImage());  //this loads the image from a file (path) to an Image object
    }
    public Background(Image img) {

        this.img = img;
       
        Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
        setPreferredSize(size);
        setSize(size);
        setVisible(true);
        System.out.println("background constructor done");
    }

    @Override
    public void paintComponent(Graphics g) {

        System.out.println("background painted");
        g.drawImage(img, 0, 0, this); //draw the image on the JPanel
    }
}

The idea is that this class represents a JPanel and it loads an image from an image file that you specify via the constructor. Afterwards, it sets the size of the JPanel equal to the size of the image and paints it on the JPanel.

Now to use this JPanel as the background for a JFrame all you have to do is:
 (Lets say this is a class that extends JFrame)
1. final String BACKGROUND_IMAGE = ".\\img\\rough_edge.png";  /*determine the path to the image file*/
pay attention to the double slashes, since a single slash indicates an escape code e.g. \n \t \b
the image is in my project folder in a folder called img, if you run the application from a jar file the img folder has to be in the same folder as the jar

2. initialize a Background object
private Background bg; //a field for the background object
/* in the constructor*/
bg = new Background(BACKGROUND_IMAGE); //initialize in constructor

3. set the JFrame's ContentPane to the JPanel with the background on it. ContentPane is the layer of the JFrame where your components (Buttons, TextFields, etc.) are located.
this.setContentPane(bg);

4. do not forget to set the layout manager for your JFrame AFTER you change the content pane to the Background object, since it changes to the layout set in the Background class, which I believe is FlowLayout (default layout for JPanel)
e.g.  this.setLayout(new FlowLayout(FlowLayout.CENTER,2,0)); //set a layout for the new content pane

Another small thing, if you want to simply change the background color of a JFrame and it doesn't work, try calling the content pane of the JFrame: this.getContentPane().setColor(Color col);

No comments:

Post a Comment