Madison Taylor Madison Taylor - 1 month ago 9
Java Question

Image displaying with file directory, but not URL

Program works when I link to an image on my program (current code). when I replace that with a URL ("http://www.digitalphotoartistry.com/rose1.jpg"), the program will run without the image being displayed. I've tried a lot of variations with no luck. Can anyone see why it's not working?

public class ImageViewer extends JFrame {

public ImageViewer() {
//create panel of actions
JPanel actionPanel = new JPanel();
actionPanel.setLayout(new GridLayout(1, 4));

actionPanel.add(new JButton("Prev"));
actionPanel.add(new JButton("Add"));
actionPanel.add(new JButton("Del"));
actionPanel.add(new JButton("Next"));


//Create panel to hold pictures
JLabel label= new JLabel(new ImageIcon("C:/Users/Madison/Desktop/capture.png"), JLabel.CENTER);
JPanel imagePanel = new JPanel(new BorderLayout());
imagePanel.add(label, BorderLayout.CENTER );

//Add contents to frame
add(imagePanel, BorderLayout.NORTH);
add(actionPanel, BorderLayout.SOUTH);
}

public static void main (String args []){
ImageViewer frame = new ImageViewer();
frame.setTitle("Title");
frame.setSize(1000, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}


}

Answer

Are you editing your code accordingly? You can't just replace the path with the url.

Try this:

URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg"); //set url
ImageIcon image = new ImageIcon(ImageIO.read(url)); //read image and create ImageIcon
JLabel label = new JLabel(image, JLabel.CENTER);    

Remember to check for IO and MalformedURL Exceptions.

Comments