简体   繁体   English

在jframe上显示图像

[英]Displaying image on jframe

import javax.swing.*;

public class test extends JFrame {

    public static void main(String args[]) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setLocation(400, 100);
        frame.setTitle("hello world");

        ImageIcon img = new ImageIcon();
        img.getClass().getResource("/testing/youlost.png");
        JPanel panel = new JPanel();
        JLabel label = new JLabel(img);
        panel.add(label);
        panel.setVisible(true);
        frame.pack();
    }
}

I run these codes in eclipse and the frame did pop up because of frame.pack() and did not give any errors but the image did not appear. 我在eclipse中运行这些代码,由于frame.pack() ,框架确实弹出了,并且没有给出任何错误,但是图像没有出现。 could someone help me with the code? 有人可以帮助我提供代码吗?

The mistake is that you are not setting the image for your ImageIcon . 错误是您没有为ImageIcon设置图像。

ImageIcon img = new ImageIcon(test.class.getResource("image.png"));    

And don't forget to add the JPanel into the JFrame . 并且不要忘记将JPanel添加到JFrame

frame.add(panel);

Full code would be, 完整的代码是

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocation(400, 100);
frame.setTitle("hello world");

ImageIcon img = new ImageIcon(test.class.getResource("image.png"));
JPanel panel = new JPanel();
JLabel label = new JLabel(img);
panel.add(label);
panel.setVisible(true);

frame.add(panel);
frame.pack();

在此处输入图片说明

I think the problem is that you call 我认为问题是你打电话

frame.setVisible(true);

right after creating the object. 在创建对象之后。 Try calling it after 请稍后再尝试

frame.pack();

In addition to that, you need to add the panel to the frame using 除此之外,您还需要使用以下方法将面板添加到框架中:

frame.add(panel);

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

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