简体   繁体   中英

Add a background image using JLabel

I'm a beginner and I'm trying to add the background image to my window using JLabal. As I know, the image added to the JLabel and add to display on the JFrame .

However, it doesn't work.

I really appreciate your help in resolving the problem.

public class frame extends JFrame {

frame(){
    final String logo = "./img/icon.png";
    final String bg = "./img/background.jpg";

    //create window
    setSize(1560, 1000);
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setTitle("Reaction Speed Test");
    setLayout(null);

    //setBackground
    ImageIcon background_image = new ImageIcon(bg);
    JLabel background = new JLabel("", background_image, JLabel.CENTER);
    background.setBounds(0, 0, 1560, 1000);
    add(background);

    //setIcon
    try {
        setIconImage(Toolkit.getDefaultToolkit().getImage(SpeedTest.class.
                getResource(logo)));
    } catch (Exception e) {
        System.out.println("Can't find icon");
    }

    setVisible(true);
    }
}

public class SpeedTest  {
    public static void main(String[] args) {
        //create window
        new frame();
    }
}

Your code works:

ImageIcon background_image = new ImageIcon(bg);
JLabel background = new JLabel("", background_image, JLabel.CENTER);

You can tell that is works by trying to put a full path for a image in your file system, like:

ImageIcon background_image = new ImageIcon("C:\\Users\\you\\Pictures\\image.png");
JLabel background = new JLabel("", background_image, JLabel.CENTER);

So we can say the problem is that your code cannot find the address "./img/background.jpg" while the class is running. You can either specify the full path like in my example, or write a code to get the full path based on the were your class is in runtime.

Example, assuming the image is in the same folder as the class, and the code is inside a JAR file:

new ImageIcon(this.getClass().getResource("background.jpg"), "")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM