Java Swingで画像表示がわからない

このQ&Aのポイント
  • Java Swingで画像を表示する方法についてわからないです。ImageIconクラスの引数にどのような値を指定すれば良いのかがわかりません。
  • プログラムの中で「ImageIcon icon = new ImageIcon("image.jpg");」の行がありますが、この部分の引数の指定方法が正しいかどうかがわかりません。私のパソコンに保存されている画像ファイルを表示するためには、どのように指定すれば良いでしょうか?
  • 上記のプログラムを実行した場合、画像が表示されませんでした。画像を表示するためにはどのような手順が必要なのか、解説とご指導をお願いします。
回答を見る
  • ベストアンサー

Jave Swing 画像表示わからない

java swingでGUIをプログラミングしている者です。 JLabelにImageIconの画像を貼り付けるプログラムです。↓ //画像を表示するプログラム //インポート import javax.swing.*; import java.awt.*; import java.awt.event.*; class gazopro extends JFrame{ JLabel l1; JButton b1; JPanel p; public static void main(String args[]) { //ウィンドウを作成また設定 gazopro frame = new gazopro(); frame.setBounds(300,200,700,400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } gazopro(){ //コンポーネントを作成 p = new JPanel(); add(p); b1 = new JButton("画像を表示"); p.add(b1); ImageIcon icon = new ImageIcon("image.jpg"); l1 = new JLabel(icon); p.add(l1); } }   わからないところは、ImageIcon icon = new ImageIcon("image.jpg");のところです。 ImageIconの引数は、プログラミングを行っているパソコン(OS は Windows)のマイコンピューター→ Cドライブ→ MyJava→ image.jpgを指定しましたがこれで合ってますか? このプログラムでは、画像が表示されませんでした。 どうすればいいでしょうか? 解説と、ご指導宜しくお願いします。

  • Java
  • 回答数2
  • ありがとう数0

質問者が選んだベストアンサー

  • ベストアンサー
  • kmee
  • ベストアンサー率55% (1857/3366)
回答No.2

OSには、「カレントディレクトリ」というものがある。 「作業フォルダ」とか「実行時ディレクトリ」とか呼ばれることもある。 ファイルの指定方法には主に次の3つ ・絶対パス ・相対パス ・ファイル名だけ 絶対パスは絶対的な一番上(ルートディレクトリ)から指定するもの。 相対パスは、カレントディレクトリをスタート地点にして、そこからの相対的な位置関係(上とか下とか)で指定するもの ファイル名だけの場合は、特に指定がなければ、相対パスに準じる。 「ファイル名だけの場合は、○○ディレクトリから検索する」等とマニュアルにあればそこから探す。 で、Swing.ImageIconのコンストラクタのマニュアルを読む http://docs.oracle.com/javase/jp/6/api/javax/swing/ImageIcon.html#ImageIcon%28java.lang.String%29 ファイル検索場所について、特に明記されていないので、 「ファイル名だけの場合は、特に指定がなければ、相対パスに準じる。」 →「相対パスは、カレントディレクトリをスタート地点にして、そこからの相対的な位置関係」 →「カレントディレクトリにある『ファイル名』のファイル」 となる。 以上のようなファイルやディレクトリについての動作は、Java全般(さらに言えば、コンピュータでのプログラム全般)について言えることです。 ファイルを読み書きするときの基本中の基本です。 しつこいようですが、まずは基本を勉強しましょうよ。 GUIの入門書や解説サイトは「Java自体はマスターしている」ことが前提で書かれてるので、このようなファイル操作の基本とか、オブジェクト指向とかについて、まったくと言っていいほど解説していません。そんなのを見様見真似でやったって、理解できるわけがありません。 足し算が理解できてないのに、教科書に載ってた微分方程式を書き写して出来る気になってるようなもんです。

その他の回答 (1)

noname#177743
noname#177743
回答No.1

デフォルトでは、プログラムのある階層にあるファイルを検索しますから、ホームディレクトリ内にあるファイルは読めません。これは、System.getPropertyを使ってホームディレクトリのパスを取得し、それにファイル名などを付け足してファイルのフルパスを生成して利用すればいいでしょう。 String filepath = System.getProperty("user.home") + File.separator + "image.jpg"; こんな感じでホームディレクトリにあるimage.jpgのファイルパスが得られると思いますので、それを指定して読み込んでみてください。

関連するQ&A

  • JAVAでの背景画像表示

    現在javaでゲームのメニュー画面を作っているのですが、ボタンを配置する所まではできたんですが、背景に画像を表示することができなくて困っています! import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.ImageIcon; import java.awt.Container; import java.awt.BorderLayout; import javax.swing.border.LineBorder; import javax.swing.border.EtchedBorder; import java.awt.Color; import java.awt.Container; public class Mati extends JFrame{ public static void main(String[] args){ Mati frame = new Mati(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(10, 10,650,650); frame.setTitle("街"); frame.setVisible(true); JPanel h = new JPanel(); h.setOpaque(false); ImageIcon icon1 = new ImageIcon("Mati.jpg"); JLabel label1 = new JLabel(icon1); JLabel label2 = new JLabel(); h.add(label1); } Mati(){ JButton button1 = new JButton("宿屋"); button1.setFont(new Font("Mairyo", Font.PLAIN, 30)); JButton button2 = new JButton("道具屋"); button2.setFont(new Font("Mairyo", Font.PLAIN, 30)); JButton button3 = new JButton("武器屋"); button3.setFont(new Font("Mairyo", Font.PLAIN, 30)); JButton button4 = new JButton("街を出る"); button4.setFont(new Font("Mairyo", Font.PLAIN, 30)); JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); p.add(Box.createRigidArea(new Dimension(10,30))); p.add(button1); p.add(Box.createRigidArea(new Dimension(5,8))); p.add(button2); p.add(Box.createRigidArea(new Dimension(5,8))); p.add(button3); p.add(Box.createRigidArea(new Dimension(5,8))); p.add(button4); getContentPane().add(p, BorderLayout.CENTER); } } ソースはこのようになっています。これからどうすれば背景画像が表示されるか教えていただきたいです。 よろしくお願いします。

  • javaでスタート画面を作っていて困っています。

    現在javaでゲームのスタート画面を作っているのですが、パネルが透過されずに困っています。 プログラムソースは import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.ImageIcon; import java.awt.Container; import java.awt.BorderLayout; import javax.swing.*; import java.awt.Font; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.*; import java.awt.event.*; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.ImageIcon; import java.awt.Container; import java.awt.BorderLayout; import javax.swing.border.LineBorder; import javax.swing.border.EtchedBorder; import java.awt.Color; import java.awt.Container; class Start最新版 extends JFrame{ public static void main(String args[]){ Start最新版 frame = new Start最新版("タイトル"); frame.setVisible(true); } Start最新版(String title){ setTitle(title); setBounds(10, 10, 1024, 768); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel p = new JPanel(); p.setOpaque( false ); ImageIcon icon1 = new ImageIcon("Start.jpg"); JLabel label1 = new JLabel(icon1); JLabel label2 = new JLabel(); p.add(label1); Container contentPane = getContentPane(); contentPane.add(p, BorderLayout.CENTER); JButton button1 = new JButton("ゲームを始める"); button1.setFont(new Font("Mairyo", Font.PLAIN, 30)); JPanel n = new JPanel(); n.setOpaque(false); n.setLayout(new BoxLayout(n, BoxLayout.Y_AXIS)); n.add(Box.createRigidArea(new Dimension(290,30))); n.add(button1); となっています。「ゲームを始める」ボタンだけを残して、周りのパネルを透過して画像を表示させたいのですが、うまくいきません!解決方法をご存知の方どうか教えていただきたいです!よろしくお願いします。

  • Javaのプログラミング手伝ってください

    以下のソースコードを応用して、添付画像のような数字のかかれた画像を3つ並べてそれを回して7を揃えるというゲームを作りたいのですが全く進みません。どなたか完成させてくださいm(__)m使用する画像のファイル名は「slot1.jpeg」~「slot7.jpeg」です。 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.Timer; public class OneSlot extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; final int MAX = 7; Timer timer = new Timer(150 , this); JLabel label= new JLabel("スタートで始まるよ",JLabel.CENTER); JButton[] bt = {new JButton("スタート"),new JButton("ストップ")}; JLabel slot= new JLabel(new ImageIcon("Slot1.jpg"),JLabel.CENTER); ImageIcon[] slot_icon = new ImageIcon[MAX]; int iCount = 0; OneSlot(String title) { super(title); timer.setActionCommand("timer"); setBounds(200, 200, 230, 150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); for(int i = 0;i < slot_icon.length; i++) slot_icon[i] = new ImageIcon("Slot" + (i+1) + ".jpg"); add("North",label); add("Center",slot); JPanel p = new JPanel(); for (int i = 0; i < bt.length;i++) { bt[i].addActionListener(this); p.add(bt[i]); } add("South",p); setVisible(true); } public static void main(String[] args) { new OneSlot("スロットマシン"); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if(cmd.equals("timer")) { if(++iCount == slot_icon.length) iCount = 0; slot.setIcon(slot_icon[iCount]); } if(e.getSource() == bt[0] && !timer.isRunning()) { label.setText("7が当たりだよ"); timer.start(); } else if(e.getSource() == bt[1] && timer.isRunning()) { if(iCount+1 == MAX) label.setText("やった!!おめでとう"); else label.setText("残念でした"); timer.stop(); } } }

  • Eclipseから実行すると画像が読み込まれない

    下記のコードをEclipseから実行すると画像が読み込まれないのですが、コマンドプロンプトから実行すると画像が読み込まれます。 コードが同じなのに不思議です…。 原因はどんなことが考えられるのでしょうか? class test extends JFrame{ public static void main(String args[]){ test frame = new test("タイトル"); frame.setVisible(true); } test(String title){ setTitle(title); setBounds(100, 100, 500, 500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel p = new JPanel(); ImageIcon icon1 = new ImageIcon("img.jpg"); JLabel label1 = new JLabel(icon1); p.add(label1); Container contentPane = getContentPane(); contentPane.add(p, BorderLayout.CENTER); } }

    • ベストアンサー
    • Java
  • 画像がうまく切り替わらない

    画像がうまく切り替わらない 初心者なため、上記の通りうまく画像を切り替えることができません。 わかる方、申し訳ありませんがご協力お願いいたします。 QUIZフォルダにあるQ1.jpg~Q80.jpgまでの画像を問題文として使った、4択のクイズ形式のプログラムを作成しています。 このプログラムなのですが、1問目と2問目はうまく表示されますが、3問目から画像が切り替わらなくなってしまっています。 swingを使い、以下のような内容でJPanel pにQ80.jpgまで切り替えていこうとしていました。 p.remove(5); ImageIcon icon1 = new ImageIcon("./QUIZ/Q2.jpg"); JLabel label1 = new JLabel(icon1); p.add(label1); new ImageIconを使いすぎなのが原因かとも思っているのですが、どのように直していいものかわからないため、ご指導お願いします。

    • ベストアンサー
    • Java
  • JavaのSwingのレイアウト

    Swingを学習中ですが、うまくレイアウトできません。 添付した画像のようなレイアウトにしたいです。 作ってみたものは以下です。 import java.awt.BorderLayout; import java.awt.Color; import javax.swing.*; public class LayoutTest { public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); JTextField searchFiled = new JTextField("テキスト"); String[] comboboxString = {"C", "C++", "Java"}; JComboBox comboBox = new JComboBox(comboboxString); JButton button = new JButton("ボタン"); panel.add(comboBox, BorderLayout.EAST); panel.add(searchFiled, BorderLayout.CENTER); panel.add(button, BorderLayout.WEST); frame.add(panel, BorderLayout.PAGE_START); JPanel redPanel = new JPanel(); redPanel.setBackground(Color.RED); frame.add(redPanel); frame.setSize(700, 500); frame.setLocationRelativeTo(null); frame.setVisible(true); } }

    • ベストアンサー
    • Java
  • 画像からヒストグラムを作りたいのですが

    画像からヒストグラムを計算し、それをグラフにしてあらわしたいと思っています。プログラムは以下のようなところまでできており、TextFieldにファイル名を入力し、EnterkeyもしくはOpenを押すと左下にその画像が表示されるところまでできています。 Startを押すと、その画像のRGBヒストグラムを計算し、赤、緑、青各色のグラフを三つ右下に表示したいのですがGraphicsの使い方や、BufferedImageの使い方がわからず四苦八苦しております。ヒストグラムをしては横区間を16としてやりたいと思っております。自分なりにはヒストグラム値を16で割り、その数値をもとにGraphicsオブジェクトに与えてそれをもとに描写するという方向で作成していましたがわたくしには難しく頓挫してしまいました。どうぞよろしくお願いいたします。 /*ここからソース*/ import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import javax.imageio.*; import java.io.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Main { public static class ActionB1 implements ActionListener { JTextField input; JLabel pict1; JFrame frame2; public ActionB1(JTextField input0,JLabel pict10,JFrame A0){ input =input0; pict1=pict10; frame2 = A0; } public void actionPerformed(ActionEvent e){ if(getClass().getResource(input.getText())==null){ pict1.setText("file not found!!!"); } else { ImageIcon temp =new ImageIcon(getClass().getResource(input.getText())); pict1.setIcon(temp); } pict1.repaint(); } } public static class ActionB2 implements ActionListener{ JLabel pict2; JTextField input; JFrame frame3; public ActionB2(JTextField input0,JLabel pict20,JFrame A0){ input =input0; pict2=pict20; frame3=A0; } public void actionPerformed(ActionEvent e){ File filename = new File(input.getText()); BufferedImage Image = null; try { Image = ImageIO.read(filename); } catch (IOException e1) { // TODO 自動生成された catch ブロック e1.printStackTrace(); } //ここからわかりません } public static void main(String[] args){ JFrame frame =new JFrame("タイトル"); frame.setSize(600,400); JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); JButton b1 =new JButton("OPEN"),b2=new JButton("START"); JTextField t1 = new JTextField(30); p1.add(t1); p1.add(b1); p1.add(b2); b1.setBounds(350,10,100,20); b2.setBounds(460,10,100,20); t1.setBounds(110,10,230,20); p1.setBounds(20,10,80,20); frame.getContentPane().add(b1); frame.getContentPane().add(b2); frame.getContentPane().add(t1); frame.getContentPane().add(p1); p2.setLayout(new GridLayout(1,2)); JLabel pict1= new JLabel(),pict2= new JLabel(); p2.add(pict1); p2.add(pict2); ActionB1 actB1 = new ActionB1(t1,pict1,frame); ActionB2 actB2 = new ActionB2(t1,pict2,frame); b1.addActionListener(actB1); b2.addActionListener(actB2); t1.addActionListener(actB1); frame.getContentPane().add(p1,BorderLayout.NORTH); frame.getContentPane().add(p2,BorderLayout.CENTER); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }

    • ベストアンサー
    • Java
  • cadで作った図面をフレーム上で表示

    こんばんは いつもお世話になっています。 gif形式の図を表示することはできるのですが AutoCADで描いた図はgifファイルに出力できません。 下記のようにコーディングしたのですが、”ぜひお越しください”しか表示されませんでした。 ほかの形式(dxf、wfm、bmp)でもいろいろ試したのですができませんでした。 どうすればAutoCADで作った図をフレーム上に表示できるのでしょうか? どなたか教えていただけませんか? import java.awt.*; import javax.swing.*; import javax.swing.ImageIcon; class map { public static void main(String args[]) { JFrame frame=new JFrame("map test"); JPanel panel=new JPanel(); ImageIcon ico=new ImageIcon("地図.gif"); JButton button=new JButton("ぜひお越しください",ico); panel.add(button); Container ct=frame.getContentPane(); ct.add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }

  • Swing自作コンポーネントをadd出来るように、

    JTextFieldやJButtonなどを一つにまとめたコンポーネントを自作し、それをadd()出来るようにしたいです。frame.add(自作のクラスのインスタンス)を可能にしたいです。 調べて、paintComponent()を使えば良いということはわかったのですが、Graphicsのインスタンス(?)に線を描いたり、円を描いたりする方法はわかりましたが、JButtonやJTextFieldなどをGraphicsのインスタンス(?)に追加する方法はわからず、paintComponent()を使うやり方はできませんでした。 paintComponent()も使わずに、自分のできる方法で、組んだものを一応載せます。 import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class MyComponentTest{ public static void main(String[] args){ JFrame frame = new JFrame("タイトル"); frame.setSize(400, 300); frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS)); // 2つのテキストフィールドと一つのボタンを4つ追加する frame.add(new TwoTextFieldsAndOneButton().getContent()); frame.add(new TwoTextFieldsAndOneButton().getContent()); frame.add(new TwoTextFieldsAndOneButton().getContent()); frame.add(new TwoTextFieldsAndOneButton().getContent()); frame.setVisible(true); } } //2つのテキストフィールドと一つのボタンを一つの部品にしたい class TwoTextFieldsAndOneButton{ JTextField textField1 = new JTextField("テキストフィールド1"); JTextField textField2 = new JTextField("テキストフィールド2"); JButton button = new JButton("ボタン"); // こんなメソッドを使わずに、再現したい JPanel getContent(){ JPanel panel = new JPanel(); panel.add(textField1); panel.add(textField2); panel.add(button); return panel; } }

    • ベストアンサー
    • Java
  • 画面を切り替えたい

    現在、ボタンを押すと 「てすと」(画像ファイル名はtest.jpg)→「てすと2」(画像ファイル名はtest2.jpg) と画面が切り替えられるプログラムを作成していますが、不明な点があり質問してみました。 2つの画面を作成してみましたが、この後どう合体すればいいのかよく分かりません。分かる方は是非教えて下さい。 <プログラムソース> (1) import java.awt.*; import java.awt.event.*; import javax.swing.*; class Title extends JFrame{ public Title() { add(new DrawPanel()); JPanel L = new DrawPanel(); L.setLayout(new BorderLayout()); JPanel L1 = new JPanel(); L1.setOpaque(false); L1.add(new JButton("OK")); L.add(L1, BorderLayout.SOUTH); setContentPane(L); } public static void main(String args[]){ JFrame frame = new Title(); frame.setSize(640, 480); frame.setTitle("てすと"); frame.setLocationRelativeTo(null); frame.setBackground(Color.pink); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);} } class DrawPanel extends JPanel{ String path = "test.jpg"; Image image; public DrawPanel() { ImageIcon icon = new ImageIcon(path); } public void paintComponent(Graphics args) { super.paintComponent(args); args.drawImage(image, 0, 0, this); args.setFont(new Font("TimesRoman",Font.ITALIC,100)); args.setColor(Color.red); args.drawString("てすと", 120, 230); } } (2) import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Title2 extends JFrame { public Title2() { add(new DrawPanel()); JPanel L = new DrawPanel(); L.setLayout(new BorderLayout()); JPanel L1 = new JPanel(); L1.setOpaque(false); L1.add(new JButton("OK")); L.add(L1, BorderLayout.SOUTH); setContentPane(L); } public static void main(String args[]){ JFrame frame = new Title2(); frame.setSize(640, 480); frame.setTitle("てすと"); frame.setLocationRelativeTo(null); frame.setBackground(Color.white); frame.setVisible(true); } } class DrawPanel extends JPanel { String path = "test2.jpg"; Image image; public DrawPanel() { ImageIcon icon = new ImageIcon(path); image = icon.getImage(); } public void paintComponent(Graphics args) { super.paintComponent(args);  args.setFont(new Font("TimesRoman",Font.BOLD,40)); args.setColor(Color.blue); args.drawString("てすと2", 150, 390); } }

    • ベストアンサー
    • Java

専門家に質問してみよう