简体   繁体   English

在原始GUI框架内显示图像

[英]Displaying Image Inside of Original GUI Frame

I have a GUI form called SimpleGUI that is just a single JPanel . 我有一个名为SimpleGUI的GUI表单,它只是一个JPanel My goal is to display my URL image inside of the that JPanel . 我的目标是在该JPanel显示我的URL图像。 When I try to add the image, I don't get an error, but nothing displays. 当我尝试添加图像时,我没有收到错误,但没有显示任何内容。 The image DOES display if I create a new JFrame and add my JPanel to that. 如果我创建一个新的JFrame并将我的JPanel添加到该图像,则显示图像。 But then I have two Windows open. 但后来我开了两个Windows。

How can I display my image in my original SimpleGUI form? 如何以原始的SimpleGUI表单显示我的图像? (Code below) (以下代码)

Thank you! 谢谢!

public class SimpleGUI extends JFrame {
private JPanel imagesPanel;
//private JFrame mainFrame;

public SimpleGUI() throws IOException {
    super("GUI Page");
    setContentPane(imagesPanel);
    pack();
    setVisible(true);
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setSize(new Dimension(500, 500));

    //mainFrame = new JFrame();



    imagesPanel.setLayout(new GridLayout());
    imagesPanel.setBounds(0,0,200,200);


    //mainFrame.add(imagesPanel);
    //mainFrame.setVisible(true);


    BufferedImage img1 = null;

    try
    {
        URL url1 = new URL("http://cosplayidol.otakuhouse.com/wp-content/uploads/2012/06/s-1-1.jpg");

        URLConnection conn1 = url1.openConnection();
        conn1.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
        InputStream in1 = conn1.getInputStream();

        img1 = ImageIO.read(in1);
    } catch (IOException e)
    {
        e.printStackTrace();
    }


    JLabel wIcon = new JLabel(new ImageIcon(img1));
    imagesPanel.add(wIcon);

  }
}

Main method: 主要方法:

public class Main {

public static void main(String[] args) {
// write your code here

    try {
        SimpleGUI simpleGUI = new SimpleGUI();
    } catch (IOException ioe){
        ioe.printStackTrace();
    }

  }
}

This code at the top of your method should be at the end. 方法顶部的代码应该在最后。 This should fix the problem 这应该可以解决问题

setContentPane(imagesPanel);
pack();
setVisible(true);

Edit: As well as fixing the problem, I should have explained why this fixes the problem. 编辑:除了解决问题,我应该解释为什么这解决了问题。 The issue is when you called pack() at the beginning of the method, nothing has been added to the imagePanel, and so the return value of getPreferredSize() is going to be very small / (0,0). 问题是当你在方法的开头调用pack()时,没有任何东西被添加到imagePanel,因此getPreferredSize()的返回值将非常小/(0,0)。 After adding your Components, it can be sized appropriately 添加组件后,可以适当调整大小

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

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