ImageIconオブジェクトからImageクラスのオブジェクトを作成する

広告

Imageクラスのオブジェクトを作成するには色々な方法がありますが、小さい画像などの場合にはImageIconクラスのオブジェクトを作成してからImageクラスのオブジェクトを作成することもできます。

Imageクラスのオブジェクトを作成するにはImageIconクラスで用意されている「getImage」メソッドを使います。

アイコンの Image を返します。

戻り値:
  この ImageIcon の Image オブジェクト

メソッドを実行すると対象にImageIconオブジェクトからImageクラスのオブジェクトを戻り値として取得できます。

実際には次のように使用します。

ImageIcon icon = new ImageIcon("./img/sample.png");
Image image = icon.getImage();

サンプルプログラム

では実際に試してみましょう。

JImageIconTest4.java

import javax.swing.*;

public class JImageIconTest4 extends JFrame{

  public static void main(String[] args){
    JImageIconTest4 frame = new JImageIconTest4();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(10, 10, 300, 200);
    frame.setTitle("タイトル");
    frame.setVisible(true);

    ImageIcon icon = new ImageIcon("./hasami.png");
    frame.setIconImage(icon.getImage());
  }
}

上記をコンパイルした後で実行すると次のように表示されます。

ImageIconからImageを取り出す

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。