0
votes

So im making a gui, and i have a background image for it. i dont know how to make it set as the background, so any help with that would be good. an explination would also be good. also, after we get that image as a background, how do we get the image resize to the size of the window. such as image.setSize(frame.getHeight(), frame.getWidth()); but i dont know if that would work. the image name is ABC0001.jpg and the frame name is frame. thanks!

2
Please search SO first. Both these questions have been asked & answered on SO many times before. - Andrew Thompson

2 Answers

3
votes

To get the image to resize, you can either use


public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), this); // draw the image
}

or you can use a componentlistener, implemented like:


        final Image img = ...;
        ComponentListener cl = new ComponentAdapter() {
            public void componentResized(ComponentEvent ce) {
                Component c = ce.getComponent();
                img = im1.getScaledInstance(c.getWidth(), c.getHeight(), Image.SCALE_SMOOTH); 
            }
        };

Image quality will degrade over time with the second solution, so it is recommended that you keep the original and the copy separate.

0
votes

Create a class the extends JPanel. Have that class load the image by overriding paintComponent

class BackgroundPanel extends JPanel
{
    Image img;
    public BackgroundPanel()
    {
        // Read the image and place it in the variable img so it can be used in paintComponent
        img = Toolkit.getDefaultToolkit().createImage("ABC0001.jpg");
    }

    public void paintComponent(Graphics g)
    {
        g.drawImage(img, 0, 0, null); // draw the image
    }
}

Now that you have this class, simply add this to your JFrame (or whereever you want the background).

//create refrence if you want to add stuff ontop of the panel
    private BackgroundPanel backGroundPanel;

//constructor
    add(backGroundPanel, BorderLayout.CENTER);

The size of the background will fill the entire frame so no need to scale it unless you want it smaller