Search code examples
javaswinguser-interfacejpeg

How do i have a background image resize in a java gui?


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!


Solution

  • 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.