代码之家  ›  专栏  ›  技术社区  ›  GregH

JAVA JPanel不显示图像

  •  0
  • GregH  · 技术社区  · 11 年前

    我目前正在从一个url中读取一张图片(谷歌街景)并将其添加到JPanel中。首先,我要获取url“ 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 回复  |  直到 11 年前
        1
  •  3
  •   Hovercraft Full Of Eels    11 年前

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

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

    我希望它会这样做,因为我已经实例化了它并对其调用了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);
    
        2
  •  2
  •   Dodd10x    11 年前

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

    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);
    
    JFrame frame = new JFrame();
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
    

    这应该会让你开始。