简体   繁体   中英

Trying to display URL image in JFrame

Trying to display a URL-image in a JFrame window. If this works correctly, when the program runs, a window should open displaying an image. Trying to experiment with URL's and hard-drive paths.

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

 class ImageInFrame {
    public static void main(String[] args) throws IOException {
    String path = "http://chart.finance.yahoo.com/z?s=GOOG&t=6m&q=l";
    URL url = new URL(path);
    BufferedImage image = ImageIO.read(url);
    JLabel label = new JLabel(new ImageIcon(image));
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(label);
    f.pack();
    f.setLocation(200,200);
    f.setVisible(true);
  }
  }

Compiles just fine, but fails to run. I've been experimenting with some YahooFinance data simply because it's fun to work with due to it's customization. Hope someone can help. Cheers.

Works fine for me...

Apart from the fact your not handling the exception (which might be useful for diagnostics) and not really loading the program within the EDT, it seems to work just fine...

在此输入图像描述

public class TestURLImage {

    public static void main(String[] args) {
        new TestURLImage();
    }

    public TestURLImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                try {
                    String path = "http://chart.finance.yahoo.com/z?s=GOOG&t=6m&q=l";
                    System.out.println("Get Image from " + path);
                    URL url = new URL(path);
                    BufferedImage image = ImageIO.read(url);
                    System.out.println("Load image into frame...");
                    JLabel label = new JLabel(new ImageIcon(image));
                    JFrame f = new JFrame();
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    f.getContentPane().add(label);
                    f.pack();
                    f.setLocation(200, 200);
                    f.setVisible(true);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }

            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM