JAVA JPanel没有显示图像

时间:2015-07-21 19:49:10

标签: java jpanel bufferedimage imageicon

我目前正在玩从网址阅读图片(谷歌街景)并将其添加到JPanel。首先,我正在使用网址“https://maps.googleapis.com/maps/api/streetview?size=600x300&location=46.414382,10.013988”并尝试从中读取图像,然后将此图像添加到我将显示的jpanel中。我没有收到任何编译或运行时错误,但JPanel永远不会弹出,所以我不知道我的图像是否在它上面。这里有什么想法吗?

编辑:为了澄清,我想弹出一个新窗口,其中包含从URL读入的图像,而不是将图像添加到现有面板

URL url = new URL("https://maps.googleapis.com/maps/api/streetview?size=600x300&location=46.414382,10.013988");
BufferedImage streetView  = ImageIO.read(url);
JLabel label = new JLabel(new ImageIcon(streetView));
JPanel panel = new JPanel();
panel.add(label);
panel.setLocation(0,0);
panel.setVisible(true);

2 个答案:

答案 0 :(得分:3)

  

我想弹出一个新窗口,该窗口会在网址中显示此图片,而不是将其添加到现有框架

我问为什么你希望这个显示为一个窗口,你说,

  

我希望它能因为我实例化它并在其上调用setVisible。

了解JPanel是一个容器组件,它包含其他组件,但没有显示完整GUI的机制。要做到这一点,您需要将它放入某种类型的顶级窗口,例如JFrame,JDialog,JApplet或JOptionPane,或放入顶层窗口中显示的另一个容器中。

然后创建一个对话框窗口并在其中显示图像。最简单的是JOptionPane:

URL url = new URL("https://maps.googleapis.com/maps/api/streetview?size=600x300&location=46.414382,10.013988");
BufferedImage streetView  = ImageIO.read(url);
JLabel label = new JLabel(new ImageIcon(streetView));
// JPanel panel = new JPanel();
// panel.add(label);

// code not needed:
// panel.setLocation(0,0);
// panel.setVisible(true);

// mainGuiComponent is a reference to a component on the main GUI
// or null if there is no main GUI.
JOptionPane.showMessageDialog(mainGuiComponent, label);

请注意,您可以将ImageIcon传递给JDialog,这也足够了

JOptionPane.showMessageDialog(mainGuiComponent, myImageIcon);

答案 1 :(得分:2)

JPanel本身不会弹出并显示任何内容。您需要将其添加到父窗口,例如JFrame或JDialog。

vector

这应该让你开始。