Jarファイル内のリソースをストリームとして読み込む
戻る
これも、Jarアーカイブ内に仕込んだ画像ファイルを読み込む方法です。
import java.awt.*;
import java.awt.event.*;
import java.awt.dnd.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;
/**
* $Id: Resource2.html,v 1.1 2009/06/22 16:11:54 kishi Exp kishi $
* @author KISHI Yasuhiro
*/
public class MyFrameTest extends JFrame {
public MyFrameTest () {
super( "JARファイルでの画像の取り扱いを試す" );
setLayout( new FlowLayout() );
try {
// 外観を設定します
UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" );
// 外観を変更します
SwingUtilities.updateComponentTreeUI( this );
} catch ( Exception e ) {
e.printStackTrace();
System.exit( -1 );
}
setBounds( 0, 0, 640, 480 );
//---------------------------------------------------------------
// 画像をローカルファイルから読み込むパターン
//---------------------------------------------------------------
// BufferedImage image = null;
// try {
// image = ImageIO.read( new File( "logo.gif" ) );
//
// } catch ( IOException ex ) {
// ex.printStackTrace();
// }
//---------------------------------------------------------------
// 画像をjarファイル内のリソースから取得する場合
//---------------------------------------------------------------
String imagePath = "logo.gif";
ImageIcon icon = new ImageIcon( getClass().getClassLoader().getResource( imagePath ) );
JLabel label = new JLabel( icon );
Container container = getContentPane();
container.add( label );
setVisible( true );
addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent ev ) {
dispose();
System.exit( 0 );
}
}
);
}
/**
* GUIを作成し表示する
*/
private static void createAndShowGUI() {
JFrame frame = new MyFrameTest();
}
public static void main( String[] args ) {
javax.swing.SwingUtilities.invokeLater( new Runnable() {
public void run() {
createAndShowGUI();
}
}
);
}
}
戻る