Question

import javax.swing.*;

public class SlideShow {
    JFrame slide = new JFrame("Slide Show");

    public SlideShow(){
        slide.setSize(300,400);
        slide.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        slide.setVisible(true);
        slide.setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        JLabel label = new JLabel(new ImageIcon("Images/picture1"));
        panel.add(label);
        slide.add(panel);
    }

    public static void main(String[] args){
        SlideShow slide = new SlideShow();

    }
}

I have to create a simple Java GUI that displays some cards. First, I just wanted to test it by displaying one card. For some reason I can't seem to figure out why nothing is being displayed.

Was it helpful?

Solution

You haven't actually used a proper file name "Images/picture1". Should be something like "Images/picture1.png" with the file format

Also image files, generally should be read from the class path, if you plan on having them embedded to the program. To do so, you will first need to put the file in the class path. With most IDE build configurations it's as simple as placing the image in the src. So

ProjectRoot
         src
            images
                  picture1.png

Then you would read it like

new ImageIcon(getClass().getResource("/images/picture1.png"));

A better approach would be to use ImageIO.read(). If the file path is incorrect, it will throw an exception, so you know where you're going wrong

Image image = ImageIO.read(getClass().getResource("/images/picture1.png"));
ImageIcon icon = new ImageIcon(image);

You will need to put it in the try/catch block

Also do what codeNinja said about the setVisible() after adding component. Also preferably pack() the frame, instead of setSize()

OTHER TIPS

You need to set the Frame visible after you add all necessary components to it. Move slide.setVisible(true); Down to the bottom of the constructor like this:

...
slide.add(panel);
slide.setVisible(true);

Alternatively you can add slide.revalidate(); at the bottom of your constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top