java - What is the correct path to display an ImageIcon png file for Windows 7? -
i wanted test having program simple png image on it. wrote short program this, can't seem path right. have checked, checked again, rechecked, , quadruple checked path name not right, image not display, no matter do. used short class wrote oracle in imageicon documentation (the creaetimageicon()
) accomplish this, doesn't seem help. i'll post entire program below, short.
package practiceimages; import java.awt.borderlayout; import java.awt.toolkit; import javax.swing.imageicon; import javax.swing.jframe; import javax.swing.jlabel; public class imageiconguitest { public static void main(string[] args) { imageiconguitest gui = new imageiconguitest(); gui.display(); } private imageicon createimageicon(string path, string description) { java.net.url imgurl = getclass().getresource(path); if (imgurl != null) { return new imageicon(imgurl, description); } else { system.err.println("couldn't find file: " + path); return null; } } private void display() { jframe frame = new jframe(); jlabel label = new jlabel(createimageicon( "users/evan/javaitems/sprites_and_other_art/green.png", "the color green")); frame.add(borderlayout.center, label); frame.setsize(500, 500); frame.setvisible(true); } }
the getresource(string)
method find resources on run-time class-path of application. since image seems application resource (i.e. supplied part of application) should put on run-time class-path.
e.g. ides have place can put resources within project structure, automatically included @ run-time. move (or copy) image path.
then becomes matter of providing correct string
. let imagine project set this:
- bin
- src
- com
- our
- application.java
- our
- resources
- green.png
- com
so application.java
in package com.our;
, while image in path resources/green.png
.
if accessing image application
, correct path (drum roll please..)
"/resources/green.png"
notes
- the leading
/
important. tells jre want image 'root of class-path', opposed using path relative package of class itself. - correct case vital. string of
"/resources/green.png"
not locate image named"/resources/green.png"
or"/resources/green.png"
.
eclipse paths
- right click on
src
directory, selectproperties
@ bottom of menu.
- navigate (using normal way you'd use without eclipse) directory of
location
. - then go parent directory.
- you should see
bin
directory contains classes , (hopefully) image.
Comments
Post a Comment