ImageIconオブジェクトからImageクラスのオブジェクトを作成する
広告
Imageクラスのオブジェクトを作成するには色々な方法がありますが、小さい画像などの場合にはImageIconクラスのオブジェクトを作成してからImageクラスのオブジェクトを作成することもできます。
Imageクラスのオブジェクトを作成するにはImageIconクラスで用意されている「getImage」メソッドを使います。
public Image getImage()
アイコンの Image を返します。 戻り値: この ImageIcon の Image オブジェクト
メソッドを実行すると対象にImageIconオブジェクトからImageクラスのオブジェクトを戻り値として取得できます。
実際には次のように使用します。
ImageIcon icon = new ImageIcon("./img/sample.png");
Image image = icon.getImage();
サンプルプログラム
では実際に試してみましょう。
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());
}
}
上記をコンパイルした後で実行すると次のように表示されます。
( Written by Tatsuo Ikura )
著者 / TATSUO IKURA
これから IT 関連の知識を学ばれる方を対象に、色々な言語でのプログラミング方法や関連する技術、開発環境構築などに関する解説サイトを運営しています。