java - 尝试在 JFrame 中显示 URL 图像

标签 java url jframe

试图在 JFrame 窗口中显示 URL 图像。如果这一切正常,当程序运行时,应该会打开一个显示图像的窗口。尝试使用 URL 和硬盘驱动器路径进行试验。

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

编译正常,但无法运行。我一直在试验一些 YahooFinance 数据,因为它是定制的,使用起来很有趣。希望有人能帮忙。干杯。

最佳答案

对我来说很好用...

除了您没有处理异常(这可能对诊断有用)并且没有真正在 EDT 中加载程序之外,它似乎工作得很好......

enter image description here

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

            }
        });
    }
}

关于java - 尝试在 JFrame 中显示 URL 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13448368/

相关文章:

javascript - 在本地使用//url

java - JPanel 中的无限循环

java - Spring Batch 子句中的准备语句

java - Java Android 中的 Double/Float 输出问题

java - java中图像的数据类型是什么

javascript - 如何向 url 添加选项值

java - Json 响应值未设置为 Bean 类

javascript - 选择选项 onclick 更改 url 或更改 div

java - 在 Java JFrame 上添加图像 - Netbeans

java - 用 Java 编写台球游戏 - 如何定义球并移动它们(通过 Graphics g)?