File Path Changing on Export - java

I'm currently trying to develop a game, and the file path is changing when I export it.
Here is the code:
package random;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Troll extends JFrame{
/**
*
*/
private static final long serialVersionUID = 4176461585360667597L;
public static BufferedImage img;
public static void main(String[] args){
File f = new File("troll.png");
try{
if(f.exists()){
System.out.println("ITS THERE! :D");
img = ImageIO.read(f);
} else {
System.out.println("DOESNT EXIST, REAL PATH IS: " + f.getAbsolutePath() );
}
}catch(Exception e){
e.printStackTrace();
}
new Troll();
}
public Troll(){
init();
}
public void init(){
setSize(1200,800);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public void paint(Graphics g){
g.drawImage(img, 500, 350, this);
}
}
When I run it through Eclipse ( The IDE I'm using ), it's running fine and it's showing the image. When I export it as a jar and convert it to an exe using Jar2Exe Software, the image does not appear and in the console it says that the absolute path for the image is on my Desktop. But when I open the exe using 7-Zip, the picture is in the exe.
How can I export it so that when the user runs it, the program can find the file path and show the image, instead of it thinking that it's on my desktop?

If you want to publish it as a jar then you need to use the Jar-specific API for reading your file. See eg. How to read a file from a jar file? (and you need to configure Eclipse to put the picture in the jar, which it sounds like you're already doing).
Also you should let us know whether it works when it's in a jar but not as an exe, that will help us narrow down where the problem may be.

I hope this is not a troll (lol)
img = ImageIO.read(this.getClass().getResource("/troll.jpg"));
You are in a jar, there is no resource file.
See that link as well: http://www.jar2exe.com/createdexe/integrate/protect
Thread.currentThread().getContextClassLoader().getResource("hello/yes.gif");

Related

Java Swing Icon wont show up [duplicate]

I tried this way, but it didnt changed?
ImageIcon icon = new ImageIcon("C:\\Documents and Settings\\Desktop\\favicon(1).ico");
frame.setIconImage(icon.getImage());
Better use a .png file; .ico is Windows specific. And better to not use a file, but a class resource (can be packed in the jar of the application).
URL iconURL = getClass().getResource("/some/package/favicon.png");
// iconURL is null when not found
ImageIcon icon = new ImageIcon(iconURL);
frame.setIconImage(icon.getImage());
Though you might even think of using setIconImages for the icon in several sizes.
Try putting your images in a separate folder outside of your src folder. Then, use ImageIO to load your images. It should look like this:
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
Finally I found the main issue in setting the jframe icon. Here is my code. It is similar to other codes but here are few things to mind the game.
this.setIconImage(new ImageIcon(getClass().getResource("Icon.png")).getImage());
1) Put this code in jframe WindowOpened event
2) Put Image in main folder where all of your form and java files are created e.g.
src\ myproject\ myFrame.form
src\ myproject\ myFrame.java
src\ myproject\ OtherFrame.form
src\ myproject\ OtherFrame.java
src\ myproject\ Icon.png
3) And most important that name of file is case sensitive that is icon.png won't work but Icon.png.
this way your icon will be there even after finally building your project.
This works for me.
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(".\\res\\icon.png"));
For the export jar file, you need to configure the build path to include the res folder and use the following codes.
URL url = Main.class.getResource("/icon.png");
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(url));
Yon can try following way,
myFrame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
Here is the code I use to set the Icon of a JFrame
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
try{
setIconImage(ImageIO.read(new File("res/images/icons/appIcon_Black.png")));
}
catch (IOException e){
e.printStackTrace();
}
Just copy these few lines of code in your code and replace "imgURL" with Image(you want to set as jframe icon) location.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create the frame.
JFrame frame = new JFrame("A window");
//Set the frame icon to an image loaded from a file.
frame.setIconImage(new ImageIcon(imgURL).getImage());
I'm using the following utility class to set the icon for JFrame and JDialog instances:
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Scanner;
public class WindowUtilities
{
public static void setIconImage(Window window)
{
window.setIconImage(Toolkit.getDefaultToolkit().getImage(WindowUtilities.class.getResource("/Icon.jpg")));
}
public static String resourceToString(String filePath) throws IOException, URISyntaxException
{
InputStream inputStream = WindowUtilities.class.getClassLoader().getResourceAsStream(filePath);
return toString(inputStream);
}
// http://stackoverflow.com/a/5445161/3764804
private static String toString(InputStream inputStream)
{
try (Scanner scanner = new Scanner(inputStream, "UTF-8").useDelimiter("\\A"))
{
return scanner.hasNext() ? scanner.next() : "";
}
}
}
So using this becomes as simple as calling
WindowUtilities.setIconImage(this);
somewhere inside your class extending a JFrame.
The Icon.jpg has to be located in myproject\src\main\resources when using Maven for instance.
I use Maven and have the structure of the project, which was created by entering the command:
mvn archetype:generate
The required file icon.png must be put in the src/main/resources folder of your maven project.
Then you can use the next lines inside your project:
ImageIcon img = new ImageIcon(getClass().getClassLoader().getResource("./icon.png"));
setIconImage(img.getImage());
My project code is as below:
private void setIcon() {
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/slip/images/cage_settings.png")));
}
frame.setIconImage(new ImageIcon(URL).getImage());
/*
frame is JFrame
setIcon method, set a new icon at your frame
new ImageIcon make a new instance of class (so you can get a new icon from the url that you give)
at last getImage returns the icon you need
it is a "fast" way to make an icon, for me it is helpful because it is one line of code
*/
public FaceDetection() {
initComponents();
//Adding Frame Icon
try {
this.setIconImage(ImageIO.read(new File("WASP.png")));
} catch (IOException ex) {
Logger.getLogger(FaceDetection.class.getName()).log(Level.SEVERE, null, ex);
}
}'
this works for me.

Resource loading problen in Java

I am new to Java and am having a problem with my JAR file loading some graphic resources. I am using IntelliJ IDEA 2021.2 (Ultimate Edition) to write my code. While in the IDE, the code work fine and the resources are loaded, but once I create the JAR file, and run it, thew graphics don't show. I should mention I do have some graphics that show, as explained below:
package com.troymarkerenterprises;
import javax.swing.*;
import java.awt.*;
import java.util.Objects;
public class ClassTopFrame extends JPanel{
public ClassTopFrame(int screenWidth, int screenHeight) {
this.setBackground(Color.BLACK);
this.setBounds(160, 0, screenWidth-160, screenHeight/2);
JLabel jl=new JLabel();
jl.setIcon(new javax.swing.ImageIcon(Objects.requireNonNull(getClass().getResource("/i_TMEA-0002-J_Logo.png"))));
this.add(jl);
}
}
This class load the image as expected. However when I try to load button images for my menu, the buttoin images do not load. Here is the class I use to create my buttons.
package com.troymarkerenterprises;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
public class TMButton extends JButton {
Font okuda;
public TMButton(String text, String color) {
try {
okuda = Font.createFont(Font.TRUETYPE_FONT, new File("res/f_okuda.ttf")).deriveFont(16.0F);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("res/f_okuda.ttf")));
} catch (IOException | FontFormatException ignored){
}
ImageIcon defaultIcon = new ImageIcon("res/b_" + color + "_default.png");
ImageIcon hoverIcon = new ImageIcon("res/b_" + color + "_selected.png");
ImageIcon disabledIcon = new ImageIcon("res/b_disabled.png");
this.setForeground(Color.BLACK);
this.setFont(okuda);
this.setText("<html><body><br><br>"+text+"</body><html>");
this.setHorizontalTextPosition(SwingConstants.CENTER);
this.setVerticalTextPosition(SwingConstants.CENTER);
this.setIcon(defaultIcon);
this.setSelectedIcon(hoverIcon);
this.setDisabledIcon(disabledIcon);
this.setMinimumSize(new Dimension(124,70));
this.setBorder(null);
this.setBorderPainted(false);
this.validate();
}
}
As I said, I am baffled as to why this is not working. I am not sure if my project structure is wrong, or if I am creating my JAR file incorrectly. To create the JAR file I am going to IntelliJ's project structure option and creating an Artifact. After I build the Artifact, I set the executable bit in my systems file explorer, and run the far file.
I would appreciate any help anyone can suggest. If I have left something out in my explanation of the problem, I have my entire app post on my GitHub page at: https://github.com/troy-marker/TMEA-0002-J.
Thanks for any assistance, Troy.
Problem is solved. Thank you to g00se for pointing out my error.
In one case, you're filling the image icons with resources, and the other you're filling them with files. You should use the former method at all times
I was trying to load the graphics two different ways, and did not realize it. Thank you for the help.

Displaying an imageicon in eclipse doesn't work

So I've just written down some simple code that just displays an image in a JButton.
What I have done is write the code:
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame{
public static ImageIcon bf;
public static JPanel p;
public static JButton b;
public static void main (String args[]){
Main main = new Main();
bf = new ImageIcon("car.png");
p = new JPanel();
b = new JButton(bf);
p.add(b);
main.add(p);
main.setVisible(true);
main.setDefaultCloseOperation(main.EXIT_ON_CLOSE);
main.setSize(600,700);
}
}
And I have copied a pic named car.png in the same folder with my class, but I can't seem to get it to work in elipse.
But when I run the same exact code in BlueJ it runs it without any known issues.
Any help woul be greately apprecciated
Thanks In advance.
change
bf = new ImageIcon("car.png");
to
URL url = Main.class.getResource("car.png");
bf = new ImageIcon(url);
Check that if car.png is under the bin directory in the filesystem (it is filtered out in Eclipse, so do it in a file explorer).
Btw I would suggest using something like ImageIO.read(Main.class.getResource("/car.png")). The reason is the following: later on you will probably package your app (into a Jar file for example). Now if you do it this way, Java is able to locate the image even if it is executed as a Jar or from

Playing audio from jar file

I have found plenty of threads on this subject but i still dont get it to work. It works easily from the compiler but not from the jar file. It seems the jar file finds the audio file but it just doest play it.
import sun.audio.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
#SuppressWarnings({"serial","restriction"})
public class JarSoundTest1 extends JFrame {
JButton button;
InputStream in;
AudioStream as;
public JarSoundTest1() throws Exception {
JOptionPane.showMessageDialog(null, this.getClass().getResource("blopp.wav"));
button = new JButton("Click to Blopp!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
in = this.getClass().getResourceAsStream("blopp.wav");
as = new AudioStream (in);
AudioPlayer.player.start(as);
JOptionPane.showMessageDialog(null, "try");
}catch(Exception ex){
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "catch");
}
}
});
add(button);
}
public static final void main(String[] args) throws Exception {
JFrame frame = new JarSoundTest1();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
The JOptionPane displays "try" every time the button is clicked, indicating the file is found i assume? Still no sound is played. I have tried using audio files placed both inside and outside the jar file. Help to understand this is much appreciated.
Ok, I got it finally. I don't think it is a sound issue I am quite sure as I can get a wav to play with code very similar to yours, it is a resource issue within jars which can be quite tricky. I would suggest the following based upon experiments in editing the above code:
getClass vs getClassLoader
If you use getClass, the path must begin with the forward slash, /. So, if your .wav is at the top level, ./blopp.wav is the way to go. So likely that is the only adjustment you will need if the .wav file is recognized by sun.audio.*.
If you can find the resource in the jar, but cannot hear audio, maybe try a different .wav file. Some good wav files are here

Loading image in Java J2ME

I have a problem with loading image with java 2ME. I have a image file "picture.png" in location drive "C:". After that I wrote my like this to show image from this location.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class ImageMidlet extends MIDlet implements CommandListener{
private Display display;
private Command exitCommand;
private Command backCommand;
private Command okCommand;
private Form form;
private ImageItem imageItem;
private Image image;
public ImageMidlet(){
display = Display.getDisplay(this);
form=new Form("");
exitCommand = new Command("Exit", Command.EXIT, 1);
backCommand = new Command("Back", Command.BACK, 2);
okCommand = new Command("OK", Command.OK, 3);
try {
image=Image.createImage("/picture.png");
imageItem=new ImageItem(null,image,ImageItem.LAYOUT_NEWLINE_BEFORE,"");
}
catch(IOException ex){
}
form.append(imageItem);
form.addCommand(okCommand);
form.addCommand(exitCommand);
form.addCommand(backCommand);
form.setCommandListener(this);
display.setCurrent(form);
}
public void commandAction(Command c,Displayable d){
}
public void startApp() {
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
It shows me this error:
Unable to create MIDlet Test.ImageMidlet
java.lang.NullPointerException
at javax.microedition.lcdui.Form.append(Form.java:638)
at Test.ImageMidlet.<init>(ImageMidlet.java:39)
at java.lang.Class.runCustomCode(+0)
at com.sun.midp.midlet.MIDletState.createMIDlet(+34)
at com.sun.midp.midlet.Selector.run(Selector.java:151)
I am starting learn to develop, so please guide to do this.
Image.createImage(String name) loads the given image as a resource. Resources are loaded with Class.getResourceAsStream(name), which looks up the resources from classpath, not from your file system root.
You should put the image file in your classpath, which is usually the final application .jar file. Usually a folder called resources or res is created under the project, where the images are placed. The contents of this folder are then copied to the .jar file. In development phase you should be able to append your resource folder to the classpath with a command-line parameter (java -cp resources in Java SE) or with a similar IDE setting.
If you are really interested in loading the images from actual file system, you can use optional FileConnection API (http://developers.sun.com/mobility/apis/articles/fileconnection/). The handset support for this API is limited though. For static images the classpath is the way to go.
As msell said - You can't access images from Your computer. Make sure that You have included the given image in midlet jar file. If You try to access it using '/picture.png', then it should be located a the root directory in jar.
First of all place your image in default package.
I have placed "My Network Places.png" in default package.
Then create MIDlet named "ImageItemExample"
then copy below code in that MIDlet file.
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class ImageItemExample extends MIDlet implements CommandListener{
private Display display;
private Command exit;
private Form form;
private ImageItem logo;
public ImageItemExample(){
form = new Form("Image Item");
exit = new Command("Exit", Command.EXIT, 0);
try{
logo = new ImageItem(null, Image.createImage("/My Network Places.png"),
ImageItem.LAYOUT_CENTER | ImageItem.LAYOUT_NEWLINE_BEFORE |
ImageItem.LAYOUT_NEWLINE_AFTER, "Roseindia");
form.append(logo);
}catch(IOException e){
form.append(new StringItem(null, "Roseindia: Image not available: "+ e));
}
}
public void startApp(){
display = Display.getDisplay(this);
form.addCommand(exit);
form.setCommandListener(this);
display.setCurrent(form);
}
public void pauseApp(){}
public void destroyApp(boolean unconditional){
notifyDestroyed();
}
public void commandAction(Command c, Displayable d){
String label = c.getLabel();
if(label.equals("Exit")){
destroyApp(true);
}
}
}
My guess is that
image=Image.createImage("/picture.png");
throws an exception which prevents the creation of a new object of type ImageItem which leaves your imageItem variable as null. This gives you the null pointer exception.
Isn't your file Picture.png and not Pictur.png?
Verify that the file picture.png actually exists
depending on the device emulator/IDE there should be a way to set the "HOME" directory for the device. In your case, this would be "C:\"

Categories