试图在JFrame中显示URL图像

A.G*_*.G. 5 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);
  }
  }
Run Code Online (Sandbox Code Playgroud)

编译得很好,但无法运行.我一直在试验一些YahooFinance数据,因为它的定制很有趣.希望有人能提供帮助.干杯.

Mad*_*mer 11

对我来说很好......

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

在此输入图像描述

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

            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • `UIManager`有许多重要的角色,我正在使用的是安装系统(在我的情况下,Windows)的外观和感觉.您可以查看[Swing组件的可视指南](http://docs.oracle.com/javase/tutorial/ui/features/components.html)以获取一些示例 (2认同)