LoginSignup
0
0

More than 3 years have passed since last update.

javaのstaticメソッドで,画像をjarファイルに含める

Last updated at Posted at 2019-09-04

Eclipseを用いてjarファイルを作成したときに画像が含まれなくて困ったときのメモ.

問題

jarファイルを作成しても画像が表示されない.
画像を読み込むメソッドはstaticである.
このままだとjarファイルに画像は含まれない.

Main.java
public static ImageIcon getImageIcon() {
    ImageIcon icon = new ImageIcon("nanase.jpg");
    return icon;
}

解決策

クラスを引数にする

Main.java
public static ImageIcon getImageIcon(Main m) {
    ClassLoader cl = m.getClass().getClassLoader();
    ImageIcon icon = new ImageIcon(cl.getResource("nanase.jpg"));
    return icon;
}

staticでないときの解決策

参照→ https://virtualwalk.hatenadiary.org/entry/20121013/1350127275

Main.java
public ImageIcon getImageIcon() {
    ClassLoader cl = this.getClass().getClassLoader();
    ImageIcon icon = new ImageIcon(cl.getResource("nanase.jpg"));
    return icon;
}

参考

https://virtualwalk.hatenadiary.org/entry/20121013/1350127275
https://www.javadrive.jp/tutorial/imageicon/index2.html
・eclipseでjarの作成 https://java.keicode.com/lang/how-to-compile-jar-with-eclipse.php

全体

Main.java
package include;
import java.awt.BorderLayout;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JFrame{

      public static void main(String[] args){
        Main frame = new Main();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(10, 10, 150, 150);
        frame.setTitle("タイトル");
        frame.setVisible(true);
      }

      Main(){
//      ImageIcon icon = this.getImageIcon();
        ImageIcon icon = Im.getImageIcon(this);
        JLabel label = new JLabel(icon);

        JPanel p = new JPanel();
        p.add(label);

        getContentPane().add(p, BorderLayout.CENTER);
      }

//    private ImageIcon getImageIcon() {
//        ClassLoader cl = this.getClass().getClassLoader();
//        ImageIcon icon = new ImageIcon(cl.getResource("nanase.jpg"));
//        return icon;
//    }
    }


class Im{
    public static ImageIcon getImageIcon(Main m) {
      ClassLoader cl = m.getClass().getClassLoader();
      ImageIcon icon = new ImageIcon(cl.getResource("nanase.jpg"));
      return icon;
     }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0