首頁  >  文章  >  Java  >  Java窗體程式呼叫靜態資源

Java窗體程式呼叫靜態資源

伊谢尔伦
伊谢尔伦原創
2016-12-05 11:41:141361瀏覽

簡介 
介紹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