0

I am trying to grab an image from online, and then use it to display on a Jframe form. The "Hello, World!" will display, but the image won't display. Any ideas guys? Cheers.

    JFrame frame = new JFrame();
    frame.setSize(400, 400);
    JLabel label = new JLabel("Hello, World!");
    String path = "http://chart.finance.yahoo.com/z?s=GOOG&t=6m&q=l";
            try {
                URL url = new URL(path);
                ImageIcon image = new ImageIcon(url);
                JLabel imageLabel = new JLabel(image);
                label.setOpaque(true);
                frame.add(imageLabel);
                frame.add(label);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            } catch (MalformedURLException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
  • Please have a look here [ask] - you need to include errors if there are any or tell us that there aren't any - cheers. – David Wilson May 17 '16 at 10:08

2 Answers2

1

The JFrame is using a BorderLayout by default, which means only one component can be shown at the (default) CENTER position.

Basically, what's happening is the label is superseding the imageLabel and is been displayed instead, try doing something like..

Example

JLabel imageLabel = new JLabel(image);
label.setOpaque(true);
frame.add(imageLabel);
//frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

See How to use BorderLayout for more details

I would also use ImageIO.read of ImageIcon to the load, at least it will throw a IOException when the image can't be loaded, see Reading/loading images for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

It seems you are behind a proxy server and your code is not able to connect to chart.finance.yahoo.com

Please add proxy settings to your program by putting actual values

    System.setProperty("http.proxyHost", "<your proxy ip>");
    System.setProperty("http.proxyPort", "<proxy port>");
    System.setProperty("http.proxyUser", "<proxy user>");
    System.setProperty("http.proxyPassword", "<proxy password>");

Alternatively you can provide these as commandline arguments as well using -D switch. For more details please see: How to use proxy from java

Community
  • 1
  • 1
Sanjeev
  • 9,876
  • 2
  • 22
  • 33