Java窗体程序调用静态资源

伊谢尔伦
伊谢尔伦 原创
2016-12-05 11:41:14 1007浏览

简介
介绍JAVA窗体程序调用图片、音频、字体三种静态资源的代码。使用这种方法调用静态资源,可以直接把静态资源打包到JAR包里。

在音频调用中,可能会由于Eclipse的原因报错,解决办法参见有关import sun.audio.AudioPlayer(或者其它文件)的问题

Demo

这是我封装的一个修改JFrame外观的类,在里面使用的就是接下来贴的方法。

函数定义
在一个类中(继承自JFrame的一个类)定义一下方法,很遗憾不能设置成静态方法跨类调用。

/**
 * 根据相对路径加载图片
 * @param path: 图片的相对路径
 * @return: 获取到的图片对象
 */public Image getImagePath(String path) {  
    Image image=null;  
    InputStream is = (InputStream) this.getClass().getClassLoader().getResourceAsStream(path);    try {
        image=ImageIO.read(is);
    } catch (IOException e) {
        e.printStackTrace();
    }    return image;  
} 
/**
 * 根据相对路径加载音频
 * @param path: 音频文件的相对路径
 * @return: 获取到的音频对象
 */public AudioStream getAudioPath(String resource){  
    InputStream is = (InputStream) this.getClass().getClassLoader().getResourceAsStream(resource);     
    AudioStream as = null;    try {
        as = new AudioStream(is);
    } catch (IOException e) {
        e.printStackTrace();
    }    return as;  
} 
/**
 * 根据相对路径加载字体
 * @param path: 字体文件的相对路径
 * @return: 获取到的字体对象
 */public Font getDefinedFont(String path) {  
    if (definedFont == null) {  
        InputStream is = null;  
        BufferedInputStream bis = null;  
        try {  
            is = (InputStream) this.getClass().getClassLoader().getResourceAsStream(path);            bis = new BufferedInputStream(is);  
            definedFont = Font.createFont(Font.TRUETYPE_FONT, bis);  
            definedFont = definedFont.deriveFont(25f);  
            definedFont = definedFont.deriveFont(Font.BOLD);
        } catch (FontFormatException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                 if (null != bis) {  
                    bis.close();  
                 }  
                 if (null != is) {  
                    is.close();  
                 }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
    return definedFont;  
}

调用方法

/*图片*/logo = getImagePath("resource/image/logo.png");
logoIcon = new ImageIcon(logo);
logoLabel = new JLabel(logoIcon);

/*字体*/titel = new JLabel(name);
titel.setFont(getDefinedFont("resource/font/叶根友毛笔特色简体.ttf"));

/*音乐*/backMusic = getAudioPath("resource/music/竹苑情歌.au");
AudioPlayer.player.start(backMusic);  /*播放背景音乐*/

关于txt
如果仅仅是读取的话,可以考虑用上述方法打入到JAR包中,但是如果涉及到修改TXT文件的内容,就不能再打入到JAR里了,那么操作的方法就是,在源码中需要操作文件的地方直接写文件名,没有路径,然后把文件保存在JAR文件的同一目录下,就可以实现文件的操作了。当然,其它资源文件也可以用这种方法访问,但是在一些具体的情况下,还是将资源文件打入到JAR包会比较方便。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。