Search code examples
javaswingwindowsizeimageicon

How can i add an image with swing and how do i make it the size of my window?


I tried to add an image to my window and make it the same size as the window but the project won't run and no image comes up, when I had the image working before it wouldn't be the size of the screen even thought I used WIDTH and HEIGHT which is what I used for the window.

import javax.swing.*;

public class Main {

    public static int WIDTH = 1000;
    public static int HEIGHT = 368;

    public static JFrame window = new JFrame();

    public static void main(String[] args) {
         CreateWindow();
    }

    public static void CreateWindow() {
        window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        window.setSize(WIDTH, HEIGHT);
        BackgroundImage();
        window.setVisible(true);
    }

    public static void BackgroundImage() {
        ImageIcon image = new ImageIcon("C:\\Users\\SamBr\\Pictures\\image.png");
        window.add(image)
        image.setSize(WIDTH, HEIGHT);
    }

}

Solution

  • Use JLabel to show your image and with getScaledInstance() method you can resize it.

    import java.awt.Image;
    
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.WindowConstants;
    
    public class Main {
    
        public static int WIDTH = 1000;
        public static int HEIGHT = 368;
    
        public static JFrame window = new JFrame();
    
        public static void main(String[] args) {
            CreateWindow();
        }
    
        public static void CreateWindow() {
            window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            window.setSize(WIDTH, HEIGHT);
            BackgroundImage();
            window.pack();
            window.setVisible(true);
        }
    
        public static void BackgroundImage() {
            ImageIcon imageIcon = new ImageIcon("C:\\Users\\SamBr\\Pictures\\image.png");
            ImageIcon scaledImage = new ImageIcon(
                    imageIcon.getImage().getScaledInstance(WIDTH, HEIGHT, Image.SCALE_SMOOTH));
            JLabel label = new JLabel();
            label.setIcon(scaledImage);
            window.add(label);
        }
    
    }