简体   繁体   English

简单的Java GUI,没有显示卡

[英]Simple Java GUI, cards not appearing

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. 我必须创建一个显示一些卡的简单Java GUI。 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. 由于某种原因,我似乎无法弄清为什么什么也不显示。

You haven't actually used a proper file name "Images/picture1" . 您实际上并没有使用正确的文件名"Images/picture1" Should be something like "Images/picture1.png" with the file format 文件格式应为"Images/picture1.png"

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 . 使用大多数IDE构建配置,就像将映像放在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() . 更好的方法是使用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 您需要将其放入try/catch块中

Also do what codeNinja said about the setVisible() after adding component. 添加组件后,还要执行codeNinja关于setVisible()内容。 Also preferably pack() the frame, instead of setSize() 还最好将框架pack()而不是setSize()

You need to set the Frame visible after you add all necessary components to it. 在将所有必需的组件添加到框架后,需要将其设置为可见。 Move slide.setVisible(true); 移动slide.setVisible(true); Down to the bottom of the constructor like this: 像下面这样构造到底部:

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

Alternatively you can add slide.revalidate(); 或者,您可以添加slide.revalidate(); at the bottom of your constructor. 在构造函数的底部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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