Creating a Pixmap in LibGDX can't find file - java

This code keeps throwing io.FileNotFoundException:
spriteBatch = new SpriteBatch();
spriteMap = new Texture(new Pixmap(new FileHandle("Sprites.png")));
spriteMap.setFilter(TextureFilter.MipMapLinearNearest, TextureFilter.MipMapLinearNearest);
spriteMap.setWrap(TextureWrap.ClampToEdge, TextureWrap.ClampToEdge);
sprites = new TextureRegion(spriteMap).split(16, 16);
any ideas what's wrong? i have also tried spriteMap = new Texture(new Pixmap(Gdx.files.internal("Sprites.png"))); but no luck...Sprites.png is just right in the package this class is in

While using this:
spriteMap = new Texture(new Pixmap(Gdx.files.internal("Sprites.png")));
be totally sure you have a file called "Sprites.png" (with the capital 'S') inside your assets folder.
assets/Sprites.png
If you have a folder between, for example data (created with the Libgdx-setup-ui by default). then you would need to put it aswell.
assets/data/Sprites.png
If you are sure the file is there. Then:
If running from eclipse, refresh your project (f5), it may be unsynchronized)
If this only happens in the Desktop project, then maybe your assets folder is not correctly linked.
Edit:
You edited your question :p
Sprites.png is just right in the package this class is in
thats your problem, Gdx.files.internal looks into the Android assets folder. not the folder in which the class is in.

Related

Why are images in my IntelliJ IDEA project accessible to some Java classes but aren't to others in JavaFX?

I'm working on a simple 2D game in JavaFX, and I loaded some of my assets (just a bunch of folders and images) into my project into their own directory, and went to make another Java class for all the stuff the player needs (movement, keypress, loading player assets), and none of the images are loading. Does anyone know why? I have the code I know is causing the problem below.
class Player
{
public Player() throws FileNotFoundException
{
System.exit(-1);
}
Image leftSide = new Image(new FileInputStream("resources/player/leftNO.png");
ImageView leftSideView = new ImageView(leftSide);
}
My directory is listed below:
.idea
out
resources
player
leftNO.png
rightNO.png
src
sample
Main.java
Player.java
Anyone know why this is happening? Thanks in advance, even if you don't have an answer.
EDIT: Also, I forgot to mention that when I try to open the image in the Main.java class, it loads fine.
When you say not loading, do you mean that it throws an exception or is blank?
Depending on which, this could work:
Mark your resources directory as a source folder and try
class Player
{
public Player() throws FileNotFoundException
{
System.exit(-1);
}
Image leftSide = new Image(getClass().getResourceAsStream("/player/leftNO.png");
ImageView leftSideView = new ImageView(leftSide);
}
This will also allow you app to work from within a jar

How to write the right URL for an image

Im making a game with JavaFX and want to load images into it. Im having trouble with finding the correct URL to load the image
Its supposed to be a Memory game and the image is supposed to be loaded into a button for the player to interact with. Normally when I tried working with images, I start the URL at the projects folder and it works fine but here I keep getting error messages. I only get it to work when I type in the full URL from the C: Drive but shouldnt it also be possible to access it just from projects folder?
This is the constructor of the class for the Memory Cards
public MemoryCard(String front, int picID)
{
front = new ImageView(front);
picBack = new ImageView("src/grafics/back.jpg");
setGraphic(picBack);
//...
}
I have created a folder called 'grafics' under the source folder with the correct images inside. I thought this would work but it just gives me the IllegalArgumentException message on the line where I load the image.

Unable to set icon for java application using setIconImage() method

I'm trying to create one simple GUI based testing tool in Java using Eclipse. I have been trying to add icon to my application. Images are present inside the project in a folder. Could you please suggest what mistake I'm doing.
I'm used below two ways, unfortunately both are not helping me. -
1.) frame.setIconImage(image).
2.) setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource(Filepath)));
Below is the setup of my project in Eclipse -
Below is code which i'm using -
public static void main(String[] args) {
JFrame frame = new JFrame("Testing Tool");
// setting close operation
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// sets 500 width and 600 height
frame.setSize(500, 600);
try {
Image image = new ImageIcon("/Project_T/Images/biplane.jpg").getImage();
frame.setIconImage(image);
} catch(Exception e) {
System.out.println("Application icon not found");
}
// uses no layout managers
frame.setLayout(null);
// makes the frame visible
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
Since i'm going to create an .exe file for this project using lunach4J, is this the way of keeping files (placing them in a folder of project since I would be using multiple images and files) that ensures the application running on any machine.
This is the code I used with a Swing application packaged in an executable JAR file. The JFrame has the icon image.
private static final String APP_ICON_PATH = "myapp/icondirectory/report.png";
ImageIcon icon = new ImageIcon(ClassLoader.getSystemResource(APP_ICON_PATH));
frame.setIconImage(icon.getImage())
The "myapp" is the root of my package structure; e,g., the GUI class using the frame is in the package myapp.gui package. The image PNG files are within the application's executable JAR file (as you see in the code within a separate folder).
Also, look at the Oracle's Java Swing tutorials explain the usage of icons.
I fiddled a lot and finally found a way out , since my explanation was a bit long so I thought of writing an answer. Also please suggest that is this a good way since we would be exporting our project.
Java gives you the power to change the ICON for your application with the help
of setIconImage(image), but this method is not that direct, since we are
dealing with multiple files those should be present while executing the code so we
would have to ensure that their paths are correct and accessible in order to run smoothly.
Hence we save our files inside the src by creating another folder and from there
we can import the files easily. Follow these steps
Step - 0 - Place the files inside src folder of the project
Put the files inside the scr folder by creating another folder, here I created another folder by the name of images and placed my files there, hence the file path would be
"Images/biplane.png",
please ensure that there are no "/" placed before Images (our folder name)
Step - 1 - Place the file path inside a URL variable
Step - 2(Optional) - Print this URL variable to cross check that this is not null. If this is null check your path again and repeat the activity so that this value is not null.
Step - 3 - Now pass this URL to ImageIcon method.
Step - 4 - Call the setIconImage method with that image.
Code Used -
URL url = test.class.getClassLoader().getResource("Images/biplane.png");
System.out.println("Path for file is :- \"" + url + "\"");
Image image = new ImageIcon(url).getImage();
frame.setIconImage(image);

How to use an image in a java project without an absolute path

I've been working in a little project to get a bit of practice programming. It's basically done, but I won't be satisfied until I can use images properly, a bit of help would be appreciated.
So, currently I'm using the the getImage method from the ImageIcon class, like so:
Image body = new ImageIcon("C:/Users/Centollo/Documents/NetBeansProjects/Chess/build/classes/chess/img/WhiteBishop.png").getImage();
I've been trying to figure out how to do the same thing without using an absolute path, but I don't know how to make the images a part of the jar so that it works fine in any other machine.
All I need to know is where to put the images and how would the code to access them look like.
Try to explain it like I'm stupid, please. I've read answers to similar questions but I can't make heads or tails of them.
I'm working in NetBeans with a "chess" package with all the .java and a "chess.img" package with all the .png.
If your class extends from JFrame, you can do this:
Image image = new ImageIcon(this.getClass().getResource("/images/MyImage.jpg")).getImage();
If your class extends Applet, you can go this way:
private URL base = null;
private Image myImage = null;
try
{
base = getDocumentBase();
} catch (Exception e)
{
e.printStackTrace();
}
myImage = getImage(base, "images/MyImage.jpg");
A very quick google search yields this:
URL resource = getClass().getClassLoader().getResource( "img/WhiteBishop.png" );
Image body = new ImageIcon( resource );
There are a couple ways to do this but here's the way I would suggest:
Make sure the chess.img folder is in your application's classpath. Then try referring to the path like chess.img/image (yes, you can use forward slash in windows.)
If that doesn't work use:
ChessClass.class.getClassLoader().loadResourceAsStream("/chess.img/image");
Note the forward slash at the beginning of the file reference. This points to the root of the classpath. It's a bit confusing as someone with unix/linux experience might think it refers to the root of the file system. This tends to work better than the other answer given for reasons I knew 10 years ago. This is an ugly bit of Java that was never quite cleaned up.

Runnable JAR file won't

I created this card game in Java. What it does it it presents one card face up and 4 more cards face down. You wager from 1 to 100 coins and try to pick a higher card from the face down cards. If you pick a higher card, your wager is doubled and you can choose to go double or nothing on another round.
The program uses 3 .java files in one package:
HigherNumber: Main class, contains the bulk of the code.
Deck: Contains definition for a class representing a deck of cards.
Card: Contains definition for a class representing an individual card.
So naturally, this program uses a lot of pictures, to represent the cards. In my original implementation, I just passed ImageIcon a string to represent the location of the cards. So like, for the icon for a face down card,
faceDown = new ImageIcon("multimedia/redBack.gif");
When I did this, the program ran perfectly when run through Eclipse. So I used Eclipse to Export to a runnable JAR file. This JAR file then ran without a problem, except if I moved the JAR file anywhere else, none of the images showed up.
So I researched and found out about using URLs to combat this. I reworked the program to use URLs, so now I have stuff like this:
//Set URL for default faceDown icon.
faceDownURL = this.getClass().getResource(pictureRoot +"redBack.gif");
//Set location for default back face of cards.
faceDown = new ImageIcon(faceDownURL);
Now it runs fine in Eclipse, but I cannot get the exported runnable JAR to work. When run from Windows, it just kinda blinks and does nothing. When I run through the command line, I get this:
C:\Documents and Settings\mstabosz>java -jar C:\Temp\HigherNumber.jar
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at higherNumber.Card.setImage(Card.java:150)
at higherNumber.Card.<init>(Card.java:36)
at higherNumber.Deck.<init>(Deck.java:22)
at higherNumber.HigherNumber.<init>(HigherNumber.java:16)
at higherNumber.HigherNumber.main(HigherNumber.java:857)
Trying to follow this code, it looks like the source of the problem is in the Card class at line 150. At line 150, the class is in the setImage() function, which is building a string called iconName to be used to set the image for each card as it is created. It then returns an ImageIcon to the Card class's constructor.
//Set up the icon for the card.
this.cardIcon = setImage();
Line 150 is the return statement. Here are the statements that create the URL cardIconURL which is used in the ImageIcon.
//Create a URL based on the constructed string.
URL cardIconURL = this.getClass().getResource(iconName);
return new ImageIcon(cardIconURL);
I just don't get what's going wrong here. The program worked fine as a runnable JAR when I was using Strings instead of URLs. It works fine when run through Eclipse. It doesn't work as a runnable JAR now.
I did read up on something called manifests, which I had trouble understanding. I did have Eclipse generate a manifest for this program:
Manifest-Version: 1.0
Main-Class: higherNumber.HigherNumber
What am I missing?
i use something like:
URL myurl = this.getClass().getResource("file.png");
myIconImage = Toolkit.getDefaultToolkit().getImage(myurl);
you're doing:
return new ImageIcon(cardIconURL);
Maybe try my second line. Also i store the images in the jar.
Okay it looks like I got the image files in the runnable JAR by dragging and dropping the "multimedia" folder which contains the pictures into the "highernumber" package in Eclipse. I'm still getting the NullPointerException though.

Categories

Resources