0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

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

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;
     }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
0
Help us understand the problem. What are the problem?