栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在运行作为JAR存档分发的项目时加载图像之类的资源

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在运行作为JAR存档分发的项目时加载图像之类的资源

首先,更改此行:

image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));

对此:

image = ImageIO.read(getClass().getResource("/resources/icon.gif"));

可以在此线程上找到有关这两种方法之间的区别的更多信息 - 加载资源的不同方法

右键单击项目的src文件夹。选择新建->包
在“ 新建软件包对话框”下,键入软件包的名称,例如resources。点击确定
右键单击资源包。选择新建->包
在“ 新建软件包对话框”下,键入软件包的名称,例如images。点击确定
现在,选择要添加到项目中的图像,将其复制。右键单击resources.images包,里面的IDE,并选择粘贴
使用最后一个链接检查现在如何以Java代码访问此文件。虽然对于此示例,将使用


getClass().getResource("/resources/images/myImage.imageExtension");

按Shift+ F10制作并运行项目。在资源和图像文件夹,将里面自动生成出来的文件夹。

快速参考代码示例(尽管需要更多详细信息,但需要一些额外的说明链接):

package swingtest;import java.awt.*;import java.awt.image.BufferedImage;import java.io.IOException;import javax.imageio.ImageIO;import javax.swing.*;public class ImageExample {    private MyPanel contentPane;    private void displayGUI() {        Jframe frame = new Jframe("Image Example");        frame.setDefaultCloseOperation(Jframe.DISPOSE_ON_CLOSE);        contentPane = new MyPanel();        frame.setContentPane(contentPane);        frame.pack();        frame.setLocationByPlatform(true);        frame.setVisible(true);    }    private class MyPanel extends JPanel {        private BufferedImage image;        public MyPanel() { try {     image = ImageIO.read(MyPanel.class.getResource("/resources/images/planetbackground.jpg")); } catch (IOException ioe) {     ioe.printStackTrace(); }        }        @Override        public Dimension getPreferredSize() { return image == null ? new Dimension(400, 300): new Dimension(image.getWidth(), image.getHeight());        }        @Override        protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, this);        }    }    public static void main(String[] args) {        Runnable runnable = new Runnable() { @Override public void run() {     new ImageExample().displayGUI(); }        };        EventQueue.invokeLater(runnable);    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/410294.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号