Problems with images when compiled - java

I have been all over the internet trying to work out how to get an image icon displayed after compiling into a runnable jar. I discovered this problem way too late, I ran my program many times before in eclipse and every thing has worked, now 6 months later with project finished, I compiled my program with eclipse and no audio or images work. Reading on the net, it says about the location of images folder should be inside jar, but mine doesnt get put there?
I have played around with the images folder moving it inside the source folder, but it didn't work. I have a feeling that it might be something to do with the path of the resource...ebut thats only guessing.
I have built a simple program that has the same results... works when ran in eclipse, but not when compiled. Could somebody show me an example by modifying my code below. Thanks in advance.
SOURCE CODE:
package ImageIcon;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Gui {
public static JLabel c;
public Gui(){
JFrame f = new JFrame();
JPanel p = new JPanel();
p.setBounds(0, 0, 120, 200);
p.setBackground(Color.black);
p.setLayout(null);
JPanel bg = new JPanel(new BorderLayout());
bg.setBounds(50, 50, 15, 15);
bg.setBackground(Color.white);
ImageIcon a = new ImageIcon("images/success.jpg");
c = new JLabel(a);
f.setSize(100, 200);
f.setLayout(null);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.add(p);
p.add(bg);
bg.add(c);
}
public static void main(String[] args) {
new Gui();
}
}

With your current directory setup, the images dir won't even get built into the jar. Try to extract it and you will most likely see that it's not in there.
You can tell by the fact that it doesn't have the little package logo in the folder, as seen here with resources
The only default directory built into the classpath (/jar) is the src. We need to either put the resources into the src
or configure the build path to include the files that are in the resources. Once we do that, we will see the little package icon inside the folder icon. That's how we know the files are on the build path
CODE we would use:
First Image: Can't, it won't work (this your current predicament)
Second Image:
ImageIcon icon = new ImageIcon(
getClass().getResource("/resources/stackoverflow.png"));
Third Image:
ImageIcon icon = new ImageIcon(
getClass().getResource("/stackoverflow.png"));
To configure the build path to use the third option, follow the instructions in Example 2 in this answer

As from your screenshot, the image exists in a folder called "images". Put it in a folder inside your classpath: src/images/success.jpg and call:
ImageIcon a = new ImageIcon(getClass().getResource("/images/success.jpg"));

Related

Program works fine in the compiler (Eclipse), but when I export it, it doesn't work

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame("Frame");
JPanel panel = new JPanel();
JButton button = new JButton("Button");
panel.setBounds(0,0,300,300);
panel.setLayout(null);
button.setBounds(120,140,60,20);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panel.setBackground(Color.GREEN);
}
});
frame.setSize(300,300);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
panel.add(button);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
So this is my code. It works perfectly until I export it as a Runnable JAR file. I'm using Eclipse as IDE and I'm on the Windows 10. When I right-click on the project and click export, I choose Runnable JAR file as an option. After that, I choose right Main class and location where I want to save my file. This is where the problem starts: When I'm choosing Library Handling option, I have 3 options.
Extract required libraries into generated JAR
Package required libraries into generated JAR
Copy required libraries into a sub-folder next to the generated JAR
And so, when I choose the option 1), this is the error message that I get: Error: A JNI error has occurred, please check your installation and try again, and then, it's followed by: A Java Exception has occurred. After that, it just closes.
When I choose the second and third option, I don't get any error message while running it, but my cursor looks like it's loading something for 1 second and that's it.
Note that this code works in Eclipse, and the problem only occurs when I export the program.
Also, this happens with every program that I try to export.
So, if you have any advice or the solution for this problem, please let me know. Thanks in advance.

How to change java icon in a JFrame

Ok so I've been researching this one quiet a bit. I am fairly new to java but thought that this one would be easy. Ive tried just about every way that has been answered on this site and still no luck, and usually when I look here I am able to find a answer that fits what I am looking for. Does anyone know how to change the Java icon in the top corner of the JFrame. I'm pretty positive that its not my file path either because all my images are in the same folder and they all work, this is the only one that I can't seem to get to work.
This is the first part my code for the main menu of my program, everything works except when i try to add the icon image. The code I've entered below does not have anything in it for the JFrame IconImage, I removed it since it didn't work. So if there is someone who knows how to get it working with this code that would be highly appreciated, thank you very much in advanced!
public class MainFrame
{
private MyPanel main;
private MyPanel2 create;
private MyPanel3 update;
private MyPanel4 find;
JFrame frame = new JFrame("Main Menu:");
public void displayGUI()
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
contentPane.setLayout(new CardLayout());
main = new MyPanel(contentPane, this);
create = new MyPanel2(contentPane);
update = new MyPanel3(contentPane);
find = new MyPanel4(contentPane);
contentPane.add(main, "Main Menu");
contentPane.add(create, "Create Part");
contentPane.add(update, "Update Part");
contentPane.add(find, "Find Part");
frame.setLocation(200, 200);
frame.setSize(700, 580);
frame.setContentPane(contentPane);
frame.setVisible(true);
}
I have an answer for you. First, make sure that the images are in a folder, not a package. Next, insert this line of code:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("path/to/image.png"));
ImageIcon icon = new ImageIcon( );
setIconImage(icon.getImage());
This code gets the image from the class path, and returns it as a image icon, and then it sets it. This should add the image icon to the application. If it doesn't, then tell me.
EDIT: After you told me that that didn't work then I decided to take a second crack at it...
First, put your images into a completely separate folder. I usually call this /res. Next, put your image in there. Now, for loading I took a completely different route. I decided to use ImageIO instead of default loading. To load the image, you use this code:
try {
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
}
catch (IOException exc) {
exc.printStackTrace();
}
ImageIO works a lot better for loading images. If this still doesn't work then please tell me.
If you want to export this as a JAR then put a folder the same name as you used in the program in the same directory as the JAR.
For example in a NetBeans project, create a resources folder in the src folder.
Put your images (jpg, ...) in there.
Whether you use ImageIO or Toolkit (including getResource),
you must include a leading / in your path to the image file:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/agfa_icon.jpg"));
setIconImage(image);
If this code is inside your JFrame class, the image is added to the frame as an icon in your title bar.
This works pretty fine for me.
Just add this after you've created your JFrame.
try {
Image image = new ImageIcon("/icons/image.jpg").getImage();
frame.setIconImage(image);
}catch(Exception e){
System.out.println("Application icon not found");
}
Paste your image icon (fav.png) in the same package first,
Write following code in constructor of JFrame:
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("fav.png")));
Note:- fav.png is the name of icon
this.setIconImage(new ImageIcon(getClass().getResource("/iconsfolder/iconsname.jpg")).getImage());
// sets the Global icon for the system
try this code put after this code:
public void displayGUI()
{

JFrame's icon not displaying

I've got a Java application with Swing's JFrame as a main GUI unit. I've set the icon to it via setIconImage(). When I run this program in NetBeans, everything works fine and the frame's icon displays. But when I compile it and try to run jar-file (with JRE7), the application has standard icon with Duke. How do I change that icon when running app outside NetBeans?
UPD:
OK, here's the code:
public static void main(String[] args) throws IOException{
URL imgUrl = Polygon.class.getResource("/imgs/icon.png");
Image img = ImageIO.read(imgUrl);
JFrame f = new JFrame();
f.setSize(new Dimension(500, 500));
f.setIconImage(img);
f.setVisible(true);
}
UPD2:
I've added this line to the end of the code:
JOptionPane.showMessageDialog(null, new ImageIcon(img));
Everything's fine with the image! It loads! BUT it's not displayed as the icon.
When you run the application from inside Netbeans, the files from your project folder are available, but if you run the compiled JAR yourself they may not.
Read this example (note the comments) to load your image properly.
Try getClass().getResource("imgs/icon.png"). It works for me. Note the difference between absolute and relative path. You may not need the leading /.

Why is there no image when running from a .jar file?

I'm trying to make my panel show image as background. I already can do that in NetBeans, but when I build my jar and run it image doesn't show there. I know I have to access it differently. I have seen many tutorials but every one of them shows how to do it with ImageIcon, but I don't need that, I need just Image. Can anyone point out what piece of code do I need to do this? Thanks.
This is my code for backgrounded JPanel:
public class JPanelWB extends JPanel { // Creates JPanel with given image as background.
private Image backgroundImage;
public JPanelWB(String fileName){
try {
backgroundImage = ImageIO.read(new File(fileName));
} catch (IOException ex) {
new JDialog().add(new Label("Could not open image."+ex.getMessage()));
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw the background image.
g.drawImage(backgroundImage, 0, 0, getWidth(),getHeight(),this);
}
}
Yeah, you're trying to read in the image as a file -- don't do that since files don't exist within a Jar file. Instead read it in as a resource.
Something like so:
public JPanelWB(String resourceName){
try {
// backgroundImage = ImageIO.read(new File(resourceName));
backgroundImage = ImageIO.read(getClass().getResource(resourceName));
} catch (IOException ex) {
new JDialog().add(new Label("Could not open image."+ex.getMessage()));
}
}
But note that resource path is different from file path. The resource path is relative to the location of your class files.
If you want to read new image and import it as background, people smarter than me already answered your question.
But, if your problem is similar to mine, then this migh help:
If you already have images to show, then the point is to call them from absolute path. Executable class form JAR will read drive created inside virtual machine, not the physical drive in your computer.
Put images in short-pathed folder like
C:\J\proj\img\
and call them with absolute path like
"C:\\J\\proj\\img\\your_image.png" // (Don't forget the double backslashes.)
(If you don't mind path lenght, leave them in image folder inside your project package, and call them from there.)
NetBeans will pack them into JAR with absolute path. On execution JRE will create JVM with that path in it, take the images from JAR and put them to that virtual path. Class will be able to find them, because it doesn't read path from physical drive, but from own virtual one newly created inside JVM.
In that case avoiding ImageIcon is just more clutter, not less.
You can add "blackBoard" as JLabel to be background to your JFrame, set its layout to null, something like this:
private JLabel blackBoard;
private JLabel noteToSelf;
//.....
blackBoard = new JLabel();
noteToSelf = new JLabel();
//.....
// putting JLabel "blackBoard" as background into JFrame
blackBoard.setIcon(new ImageIcon("c:\\Java\\images\\MarbleTable.png"));
getContentPane().add(blackBoard);
blackBoard.setBounds(1, 1, 400, 440);
blackBoard.setLayout(null);
and then add components into "blackBoard" instead of your JFrame, like this.
// putting JLabel "noteToSelf" onto background
noteToSelf.setIcon(new ImageIcon("c:\\Java\\images\\Sticker_a1.png"));
// or: noteToSelf.setText("Remind me at 6:30am...");
blackBoard.add(noteToSelf);
noteToSelf.setBounds(noteX, noteY, 64, 48);
Now your JFrame is table board and "blackBoard" is table sheet on it.
Hope this helps.

Having difficulty add a custom icon to a JFrame

I have been trying to change the icon in the frame. I have virtually tried everything:
The icon is 16x16 which is the right size ....doesn't work
I've trying PNG,GIF and JPG formats none of them work.
Tried different way of setting the icon....doesn't work.
I've tried relative (local paths) e.g. "icon.gif" and absolute paths e.g. "c:\work\java\icon.gif" ...doesn't work
Here is my code and see if you can figure it out
Thanks
Oli
import javax.swing.*;
public class androidDriver
{
public static void main(String[] args) throws IOException
{
JFrame f = new JFrame("Android Data Viewer");
f.setResizable(false);
f.setSize(300,300);
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setIconImage(new ImageIcon("androidIcon2.gif").getImage());
}
}
If you put the image in the same directory as the class file then the following should work for you:
f.setIconImage(new ImageIcon(androidDriver.class.getResource("androidIcon2.gif")).getImage());
Also would suggest setting the icon image before you make the frame visible
f.setIconImage(new ImageIcon(androidDriver.class.getResource("androidIcon2.gif")).getImage());
f.setVisible(true);
I suspect you may have to actually wait for the image to load using a MediaTracker. It's likely that the image is still loading at the point the frame setIconImage references it, so it does nothing.
Have you tried using Toolkit.getDefaultToolkit().getImage("androidIcon2.gif")
And two other things:
Does the image exist? The code you posted will fail silently.
Is it formatted properly? (though I assume Java could handle it if it wasn't)
Make a separate folder next to the source folder then put your image in there, and then use ImageIO to get the image like so:
f.setIconImage(ImageIO.read(new File("res/androidIcon2.gif")));
Also, if that doesn't work, try saving the image as a .png instead of a .gif.

Categories