URL for image files are null while executing jar [duplicate] - java

So I am making a basic text adventure game using Java, and I have decided to include images.
The code I use to load my images onto the program is this:
imagePanel = new JPanel();
imagePanel.setBounds(50, 50, 400, 260);
imagePanel.setBackground(Color.BLACK);
con.add(imagePanel);
imageLabel = new JLabel();
image = new ImageIcon(".//res//towngate.jpg");
imageLabel.setIcon(image);
imagePanel.add(imageLabel);
When I run the program in eclipse everything works perfectly fine, but when I export it as a jar none of the images appear.
If anyone could help me fix this I would greatly appreciate it. Thanks!

Be sure that your icon is included to the jar file, and try to find in runtime with a classloader. (Example below) Don't use any relative or absolute path just use the file name:
public ImageIcon loadIcon(String iconName) throws IOException {
ClassLoader loader = this.getClass().getClassLoader();
BufferedImage icon =
ImageIO.read(loader.getResourceAsStream(iconName));
return new ImageIcon(icon);
}

Related

Adding ImageIcon to JTabbedPane

I am attempting to add a picture to the first tab of a JTabbedPane, here is my code:
JTabbedPane application = new JTabbedApplication();
JPanel welcomePanel = new JPanel();
JLabel imageLabel = new JLabel(new ImageIcon("track.jpg"));
welcomePanel.add(imageLabel);
application.addTab("WELCOME", welcomePanel);
application.setMnemonicAt(0, KeyEvent.VK_1);
The image file is located in the same location as the class this code is in. For some reason, however, my image is not appearing. I have used the same JLabel and used text instead of an image and it appears. Can someone give me some insight into this problem?
Java doesn't know that the image is located directly beside the running class file. You have to hand in the absolute path. Which means Path + filename.
This little piece of code will help you to tell Java that the image is in the current working directory.
String file = new File("track.jpg").getAbsolutePath();
Added to your code snipped it looks like this:
JTabbedPane application = new JTabbedPane();
JPanel welcomePanel = new JPanel();
String file = new File("track.jpg").getAbsolutePath();
JLabel imageLabel = new JLabel(new ImageIcon(file));
welcomePanel.add(imageLabel);
application.addTab("WELCOME", welcomePanel);
The image file is located in the same location as the class this code is in
Instead of JLabel imageLabel = new JLabel(new ImageIcon("track.jpg")); which is looking for a file in the current working directory, you should be using Class#getResource which will return a URL to the embedded resource.
It's important to note, that resources which are store within the application context (ie embedded inside the Jar or within the source packages) aren't accessible as "files" anymore.
Instead, you could try using something like...
ImageIcon icon = new ImageIcon(ImageIO.read(getClass().getResource("track.jpg"));
to load the image. Unlike ImageIcon, ImageIO.read will throw an IOException if the image can't be read, which is always more useful than the silence that you get from ImageIcon
If this fails to work, more context on the structure of your app will be needed

javafx - load image from within a jar

I'm sorry for asking such a beginner question, but I just can't get it to work and I can't find the answer anywere either.
I want to have an image inside my .jar file and load it. While that sounds simple, I was only able to load an image while running from inside the IDE but not anymore after making the .jar (Thanks to google I was able to get the .png inside the .jar). Here is what I tried:
BorderPane bpMain = new BorderPane();
String fs = File.separator;
Image imgManikin;
try {
imgManikin = new Image(
Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().toString()+"\\manikin.png");
bpMain.setBottom(new Label(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().toString()+"\\manikin.png"));
} catch (URISyntaxException e) {
imgManikin = new Image(
Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"\\manikin.png");
System.out.println(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"\\manikin.png");
bpMain.setBottom(new Label(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"\\manikin.png"));
}
//Image imgManikin = new Image("file:src\\manikin.png");
ImageView imgvBackground = new ImageView(imgManikin);
imgvBackground.setFitWidth(100);
imgvBackground.setPreserveRatio(true);
bpMain.setCenter(imgvBackground);
primaryStage.setTitle("Kagami");
primaryStage.setScene(new Scene(bpMain, 300, 275));
primaryStage.show();
Needlessly to say it didn't work. It is showing me the Label at the bottom with the path just as intended, but it seams like the path just isn't right. (I also tried using the File.seperator instead of \\ and even /, but I got the same result every time: It showes me the path but won't load the image.
I'm using Windows 7, the IDE is IntelliJ and I have the newest Java update.
If the jar file is on the classpath of your application and the image to be loaded is located at the root of the jar file, the image can be loaded easily by:
URL url = getClass().getResource("/manikin.png");
BufferedImage awtImg = ImageIO.read(url);
Image fxImg = SwingFXUtils.toFxImage(awtImg, new Image());
Image fxImgDirect = new Image(url.openStream());
While ImageIO returns a BufferedImage this can be converted to a fx Image using the SwingUtils. However the preferred way is to directly create a new Image instance using the InputStream from the URL.
See also Load image from a file inside a project folder. If done right it does not matter if it is loaded from a jar file or the local file system.
The Image::new(String) constructor is looking for a URL. It is possible to construct a URL for a resource in a jar file, but it's much easier to use ClassLoader::getResource or ClassLoader::getResourceAsStream to manage that for you.
Given the file structure:
src/
SO37054168/
GetResourceTest.java
example/
foo.txt
The following, packaged as a jar will output
package SO37054168;
public class GetResourceTest {
public static void main(String[] args) {
System.out.println(GetResourceTest.class.getClassLoader().getResource("example/foo.txt"));
System.out.println(GetResourceTest.class.getClassLoader().getResourceAsStream("example/foo.txt"));
}
}
jar:file:/home/jeffrey/Test.jar!/example/foo.txt
sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream#7f31245a
Note how the URL for the resource is not the same as the URL you were trying to construct. The protocol is different, and you need to have the ! after the path to the jar file.

How do I add an image to JPanel using imageicon (Java GUI)?

I looked all over the place but I am still stuck on how directory works to find the image to put onto the JPanel. Where is the image supposed to be? I clicked on properties for my image and it shows Location: C:\Users\Joseph\Pictures\Background and the picture's name is random.jpg.
I am trying to add an image to a tab using tabbedPane. Here is what I have so far, and I am not able to do it.
JPanel flPanel = new JPanel();
flPanel.setLayout(new FlowLayout());
ImageIcon image = new ImageIcon(getClass().getResource(""));
// Tried /Users/Joseph/Pictures/Background/random.jpg and doesn't work
JLabel j1 = new JLabel(image);
flPanel.add(j1);
tabbedPane.add("Tab 2", flPanel);
Is the picture supposed to be in the same package file as the project? Or is it supposed to be in the source file to be able to just do "random.jpg"?
If you want the image to be available to your application at runtime, then you should consider making sure that the image is included within your Jar when you application is built.
From the sounds of it, you are using Netbeans, you should copy the image to a directory within your src directory of your project.
You should then be able to use...
BufferedImage bi = ImageIO.read(getClass().getResource("/full/path/to/image/random.jpg"));
ImageIcon image = new ImageIcon(bi);
The path to the image should be the full path (from the context of the src directory) within your project.
That is, if you placed the image in the resources directory within the src directory, then you would use /resources/random.jpg as the path/file name
Take a look at Reading/Loading an Image for more details
getClass().getResource(...) will only get resources inside the classpath.
You can use ImageIO.read(File) like this:
BufferedImage bi = ImageIO.read(new File("C:\\Users\\Joseph\\Pictures\\Background\random.jpg"))
ImageIcon image = new ImageIcon(bi);

how to display image using its path

i have a the path of an image in a string i want to display it on a jlabel using the path. please help me.
if(!ar.get(16).equals("empty")){
String photo=(String)ar.get(16);
System.out.println(photo);
// if(!photo.equals(""))
// pic.setText(photo);
Image image=Toolkit.getDefaultToolkit().getImage(photo);;
ImageIcon img=new ImageIcon(image.getScaledInstance(view.jLabel5.getWidth(), view.jLabel5.getHeight(), 0));
//JpegReader jrdr=new JpegReader();
//view.jLabel5.setSize(img, image.getWidth());
view.jLabel5.setPreferredSize(new Dimension(100, 100));
view.jLabel5.setIcon(img);
}
If the image is an embedded resources (ie lives within the application context/is bundled with the application Jar), then you need to use getResource to gain access to it..
Toolkit.getDefaultToolkit().getImage expects that the String passed to it is a file on the file system.
If the image is embedded, then you will need to use something more like...
Toolkit.getDefaultToolkit().getImage(getClass().getResource(photo))
To load it.
If the image is being loaded from the file system, you could use
File file = new File(photo);
if (file.exists()) {
// Attempt to load the image
} else {
// Show error message.
}
Because of the way Toolkit#getImage works, it will not provide any details if the image fails to load for some reason.
Instead, you should be using ImageIO, which will throw an IOException if it was unable to load the image for some reason...
BufferedImage img = ImageIO.read(getClass().getResource(photo));
or
BufferedImage img = ImageIO.read(new File(photo));
Depending on where the image is located.
Take a look at Reading/Loading an Image.
You should also avoid calling setPreferredSize explicitly and simply allow JLabel to make it's own choices...
Put the image file in the project. Under a seperate folder.
ImageIcon image = new ImageIcon(this.getClass().getResource("/images/abc.jpg"));
JLabel imageLabel = new JLabel(image, JLabel.CENTER);
If you want to load the image for any other location on your computer then,
ImageIcon image = new ImageIcon("C:/images/image.png");
JLabel imagelabel = new JLabel(image);
Make sure your paths are correct. If you photo string path is "photo.jpeg", your path should look something like this
ProjectRoot
photo.jpeg
src
If you want to put the photo.jpeg in a directory images, you should use "images/photo.jpeg"
ProjectRoot
images
photo.jpeg
src
This is considering you're using an IDE like Netbeans or Ecplise.

Locating resource in Jar

I am having difficulty creating the image icon. I want to package a jar and have the images available to be displayed in the gui. Both of the following throw null pointer exceptions. The path is a path directly to a package in my Eclipse project that contains the necessary images.
ImageIcon icon = new ImageIcon(this.getClass().getClassLoader().getResource(
"/TicTacToe/src/edu/luc/tictactoe/gui/resources/images/TicTacToeOIcon.png")
.getPath());
and
ImageIcon icon = new ImageIcon(getClass().getResource(
"/TicTacToe/src/edu/luc/tictactoe/gui/resources/images/TicTacToeOIcon.png"));
I can't see to be able to access the appropriate package. Any suggestions?
ImageIcon icon = new ImageIcon(this.getClass().getClassLoader()
.getResourceAsStream("edu/luc/tictactoe/gui/resources/images/TicTacToeOIcon.png");
Try like this
JButton myButton =new JButton(“press me”);
myButton.setIcon(new ImageIcon(image));
EDIT:
Refer to this discussion to know loading the image from executable Jar files

Categories

Resources