GregH
GregH

Reputation: 5461

JAVA JPanel not displaying image

I am currently playing around with reading an image (a google street view) from a url and adding it to a JPanel. To start, I am taking the url "https://maps.googleapis.com/maps/api/streetview?size=600x300&location=46.414382,10.013988" and trying to read an image from it then add this image to a jpanel I will display. I am not receiving any compilation or runtime errors, however the JPanel never pops up so I cannot tell if my image is on it or not. Any ideas here?

Edit: To clarify, I want to pop up a new window containing the image read in from the URL, not add the image to an existing panel

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);

Upvotes: 0

Views: 993

Answers (2)

Dodd10x
Dodd10x

Reputation: 3349

A JPanel by itself will not popup and display anything. You need to add it to a parent window, such as a JFrame or a 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);

That should get you started.

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285450

I want to pop up a new window which will display this image in the URL, not add it to an existing frame

I asked why you would expect this to display as a window, and you stated,

I would expect it to because I have instantiated it and call setVisible on it.

Understand that a JPanel is a container component that holds other components but doesn't have the machinery to display a full GUI. To do this you would need to place it into some type of top-level window such as a JFrame, JDialog, JApplet or JOptionPane or into another container that is displayed in a top level window.

Then create a dialog window and display the image in it. Simplest would be a 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);

Note that you could just pass the ImageIcon into the JDialog and it would be sufficient too

JOptionPane.showMessageDialog(mainGuiComponent, myImageIcon);

Upvotes: 3

Related Questions