Image not found in LibGDX - java

SOLVED, sorry!
I'm following this tutorial here: http://www.gamefromscratch.com/post/2013/10/02/LibGDX-Tutorial-3-Basic-graphics.aspx
For some reason, when running the code provided in that URL, an error comes back telling me that the image cannot be found, which is easily understandable. However, I cannot figure out why this error is coming at me.
Here is the error I am getting, just in case:
> Exception in thread "LWJGL Application"
> com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load file:
> /data/jet.png at
> com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:140) at
> com.badlogic.gdx.graphics.glutils.FileTextureData.prepare(FileTextureData.java:64)
> at com.badlogic.gdx.graphics.Texture.load(Texture.java:142) at
> com.badlogic.gdx.graphics.Texture.<init>(Texture.java:133) at
> com.badlogic.gdx.graphics.Texture.<init>(Texture.java:112) at
> com.badlogic.gdx.graphics.Texture.<init>(Texture.java:104) at
> com.me.mygdxgame.MyGdxGame.create(MyGdxGame.java:18) at
> com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:137)
> at
> com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:115)
> Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found:
> \data\jet.png (Internal) at
> com.badlogic.gdx.files.FileHandle.read(FileHandle.java:134) at
> com.badlogic.gdx.files.FileHandle.readBytes(FileHandle.java:218) at
> com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:137) ... 8 more
Here is the code:
package com.me.mygdxgame;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class MyGdxGame implements ApplicationListener {
private SpriteBatch batch;
private Texture texture;
private Sprite sprite;
#Override
public void create() {
batch = new SpriteBatch();
texture = new Texture(Gdx.files.internal("data/jet.png"));
sprite = new Sprite(texture);
}
#Override
public void dispose() {
batch.dispose();
texture.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.begin();
sprite.draw(batch);
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
Here is my directory to the image:
C:\Android\projects\my-gdx-game-android\assets\data
Here is the directory in Eclipse:
So it looks like the image is not included in the project... How do I import it?

Refresh your project, right click over the project > Refresh or F5, so you can load the "jet.png" resource.
If you load the image directly on your Eclipse´s project explorer you will have no problems, but if you load only in Windows Explorer you have to refresh your project.

Solved using Import... -> File System -> Find my images and add them to the project.

First you can write this code
texture = new Texture(Gdx.files.internal("data/jet.png"));
like this (both right)
texture = new Texture("jet.png");
Second Make sure your file name dosn't have space before first letter (in asset folder)
cause reading " jet.png" is different from "jet.png"
Third Clean & refresh your project
Clean
1- Project ---> Clean
Refresh Gradle 2- Right Click ---> Cradle ---> Refresh All
Make sure you import files by drag and copy don't link it
your game desktop project ----> assets Drag your files & make sure you choose Copy

Related

LibGDX, GDX.files.internal() File not found

I have an issue using LibGDX with assets directory. I actually build my project folder this way. I follow this tutorial to learn. (I work on Eclipse)
The code I use is :
package com.mygdx.game;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
public class MyGdxGame implements ApplicationListener {
private SpriteBatch batch;
private TextureAtlas textureAtlas;
private Sprite sprite;
private int currentFrame = 1;
private String currentAtlasKey = new String("0001");
#Override
public void create() {
batch = new SpriteBatch();
// THE PROBLEM IS UNDER THIS LINE
textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheet.atlas"));
AtlasRegion region = textureAtlas.findRegion("0001");
sprite = new Sprite(region);
sprite.setPosition(120, 100);
sprite.scale(2.5f);
Timer.schedule(new Task(){
#Override
public void run() {
currentFrame++;
if(currentFrame > 20)
currentFrame = 1;
// ATTENTION! String.format() doesnt work under GWT for god knows why...
currentAtlasKey = String.format("%04d", currentFrame);
sprite.setRegion(textureAtlas.findRegion(currentAtlasKey));
}
}
,0,1/30.0f);
}
#Override
public void dispose() {
batch.dispose();
textureAtlas.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
sprite.draw(batch);
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
(if the code is hard to read I use exactly the same code that is in the tutorial linked below)
My package explorer looks like this :
imgur link
And it returns me :
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: File not found: spritesheet.atlas (Internal)
at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:136)
at com.badlogic.gdx.graphics.g2d.TextureAtlas$TextureAtlasData.(TextureAtlas.java:103)
at com.badlogic.gdx.graphics.g2d.TextureAtlas.(TextureAtlas.java:231)
at com.badlogic.gdx.graphics.g2d.TextureAtlas.(TextureAtlas.java:226)
at com.badlogic.gdx.graphics.g2d.TextureAtlas.(TextureAtlas.java:216)
at com.mygdx.game.MyGdxGame.create(MyGdxGame.java:23)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:149)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)
I tried some trick like Project>Clean, refreshing, close and re-open Eclipse and even recreated a project. Any idea ?
Okay, I found the trick. For those which encounter the same issue (working on Eclipse but it's pretty the same whatever the IDE is) there is one thread on stack overflow already existing which give additional solutions.
For me I had to set-up the "working directory" (for the desktop main for exemple). To do this go on Run>Run configuration>Arguments and at working directory's section there is Default and Other. Tick Other's box and me I had to write ${workspace_loc:my-gdx-game-core/assets} but I think it works like ${workspace_loc:[name-of-your-core-directory]/assets}. Hope it helped.
maybe you haven't linked the asset folder, if so,
try right click on my-gdx-game-desktop, in properties dialog select Java Build Path, click link source button, then navigate to the assets folder.
if you're already set it, try readd with this step, restart eclipse if needed

Java Swing error Exception in thread “AWT-EventQueue-0” java.lang.IllegalArgumentException: input == null [duplicate]

I am having a error for my GUI. Trying to set title bar icon then be included in a Runnable JAR.
BufferedImage image = null;
try {
image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));
}
catch (IOException e) {
e.printStackTrace();
}
frame.setIconImage(image);
Here is the error I am getting:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at GUI.<init>(GUI.java:39)
at GUI.main(GUI.java:351)
The image is in the correct directory which "resources" folder is the root of the
project file
First of all, change this line :
image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));
to this :
image = ImageIO.read(getClass().getResource("/resources/icon.gif"));
More info, on as to where lies the difference between the two approaches, can be found on this thread - Different ways of loading a Resource
For Eclipse:
How to add Images to your Resource Folder in the Project
For NetBeans:
Handling Images in a Java GUI Application
How to add Images to the Project
For IntelliJ IDEA:
Right-Click the src Folder of the Project. Select New -> Package
Under New Package Dialog, type name of the package, say resources. Click OK
Right Click resources package. Select New -> Package
Under New Package Dialog, type name of the package, say images. Click OK
Now select the image that you want to add to the project, copy it. Right click resources.images package, inside the IDE, and select Paste
Use the last link to check how to access this file now in Java code. Though for this example, one would be using
getClass().getResource("/resources/images/myImage.imageExtension");
Press Shift + F10, to make and run the project. The resources and images folders, will be created automatically inside the out folder.
If you are doing it manually :
How to add Images to your Project
How to Use Icons
A Little extra clarification, as given in this answer's first
code example.
QUICK REFERENCE CODE EXAMPLE(though for more detail consider, A little extra clarification link):
package swingtest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 7/1/14
* Time: 9:44 AM
* To change this template use File | Settings | File Templates.
*/
public class ImageExample {
private MyPanel contentPane;
private void displayGUI() {
JFrame frame = new JFrame("Image Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new MyPanel();
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private class MyPanel extends JPanel {
private BufferedImage image;
public MyPanel() {
try {
image = ImageIO.read(MyPanel.class.getResource("/resources/images/planetbackground.jpg"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return image == null ? new Dimension(400, 300): new Dimension(image.getWidth(), image.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new ImageExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
There's a much easier way to load and set an image as a frame icon:
frame.setIconImage(
new ImageIcon(getClass().getResource("/resources/icon.gif")).getImage());
And thats all :)! You don't even have to use a try-catch block because ImageIcon does not throw any declared exceptions. And due to getClass().getResource(), it works both from file system and from a jar depending how you run your application.
If you need to check whether the image is available, you can check if the URL returned by getResource() is null:
URL url = getClass().getResource("/resources/icon.gif");
if (url == null)
System.out.println( "Could not find image!" );
else
frame.setIconImage(new ImageIcon(url).getImage());
The image files must be in the directory resources/ in your JAR, as shown in How to Use Icons and this example for the directory named images/.

Java Applet not displaying image (IntelliJ)

I'm trying to get a basic Java applet displaying a simple image up and running but for some reason (I suspect a path issue or a IntelliJ setting I'm not familiar with) it's not showing up.
Here's my code:
import java.applet.Applet;
import java.awt.*;
public class Main extends Applet{
private Image logo;
#Override
public void init() {
logo = getImage(getDocumentBase(), "image.jpg");
}
#Override
public void paint(Graphics g) {
g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
g.drawImage(logo, 10, 10, this);
}
}
The image is located in the same directory as the code itself.
Any idea what's going on here?
Thanks
Try putting that image in a folder 'Resources' in your project.
Also right click that folder -> Mark as Resources. I did this many times and it worked

LibGDX -> Exception in LWJGL App - cannot be cast to

I hope you can help me and I hope I did not overlook any relevant answers.
So I get this Exception when I try and run my DesktopLauncher.java class.
Executing: gradle run
Configuration on demand is an incubating feature.
warning: [options] bootstrap class path not set in conjunction with -source 1.6
1 warning
:core:compileJava
:core:processResources UP-TO-DATE
:core:classes
:core:jar
warning: [options] bootstrap class path not set in conjunction with -source 1.6
1 warning
:desktop:compileJava
:desktop:processResources UP-TO-DATE
:desktop:classes
Exception in thread "LWJGL Application" java.lang.ClassCastException: com.bluemoon.game.MainGame cannot be cast to com.badlogic.gdx.InputProcessor
at com.bluemoon.game.MainGame.create(MainGame.java:30)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:136)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
:desktop:run
BUILD SUCCESSFUL
Total time: 4.267 secs
I just copied the my code from this tutorial.
This is my MainGame.java from the core files
package com.bluemoon.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
public class MainGame extends ApplicationAdapter {
Texture img;
TiledMap tiledMap;
OrthographicCamera camera;
TiledMapRenderer tiledMapRenderer;
#Override
public void create () {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false,w,h);
camera.update();
tiledMap = new TmxMapLoader().load("basic_map.tmx");
tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap);
Gdx.input.setInputProcessor((InputProcessor) this);
}
#Override
public void render () {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
tiledMapRenderer.setView(camera);
tiledMapRenderer.render();
}
}
And this is my DesktopLauncher.java
package com.bluemoon.game.desktop;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.bluemoon.game.MainGame;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.fullscreen = true;
cfg.resizable = false;
new LwjglApplication(new MainGame(), cfg);
}
}
When I run the DesktopLauncher.java, the program is built, then the screen turns black (probably because it's going into full screen mode). After about 1-2 seconds the program crashes.
I'm using gradle a packet management system, if that's important.
It is because MainGame class doesn't implement InputProcessor class. It should be:
public class MainGame extends ApplicationAdapter implements InputProcessor {
Of course, you will have to implement all methods from InputProcessor.

Libgdx tween not working on Android

I'm developing my first android game with libgdx, using as a base this amazing tutorial (http://www.kilobolt.com/day-11-supporting-iosandroid--splashscreen-menus-and-tweening.html). Everything works properly except for the tweening that I’m using in the splash screen to show the logo of my “company”. The weird part is that the logo works just fine in the desktop version, but in the android version is not being showed.
I’m using the same class that they used in the app developed in the tutorial. By the way, this app’s splash screen works fine in both versions.
I have compared my app and the tutorial’s app, but I found no differences except for this on the package explorer. I don't know if it means something:
http://i1223.photobucket.com/albums/dd507/victormmenendez/tut.jpg
package com.victor.Screens;
import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;
import aurelienribon.tweenengine.TweenEquations;
import aurelienribon.tweenengine.TweenManager;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.victor.TweenAccessors.SpriteAccessor;
import com.victor.FZHelpers.AssetLoader;
import com.victor.FZombies.FZGame;
public class SplashScreen implements Screen
{
private TweenManager manager;
private SpriteBatch batcher;
private Sprite sprite;
private FZGame game;
public SplashScreen(FZGame game)
{
this.game = game;
}
#Override
public void show()
{
sprite = new Sprite(AssetLoader.logo);
sprite.setColor(1, 1, 1, 0);
float width = Gdx.graphics.getWidth();
float height = Gdx.graphics.getHeight();
float desiredWidth = width * .4f;
float scale = desiredWidth / sprite.getWidth();
sprite.setSize(sprite.getWidth() * scale, sprite.getHeight() * scale);
sprite.setPosition((width / 2) - (sprite.getWidth() / 2), (height / 2) - (sprite.getHeight() / 2));
setupTween();
batcher = new SpriteBatch();
}
private void setupTween()
{
Tween.registerAccessor(Sprite.class, new SpriteAccessor());
manager = new TweenManager();
TweenCallback cb = new TweenCallback()
{
#Override
public void onEvent(int type, BaseTween<?> source)
{
game.setScreen(new GameScreen());
}
};
Tween.to(sprite, SpriteAccessor.ALPHA, .8f).target(1).ease(TweenEquations.easeInOutQuad).repeatYoyo(1, .4f).setCallback(cb).setCallbackTriggers(TweenCallback.COMPLETE).start(manager);
}
#Override
public void render(float delta)
{
manager.update(delta);
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batcher.begin();
sprite.draw(batcher);
batcher.end();
}
}
Thank you very much for your help. I'm sorry if in any moment I couldn’t explain myself, but English is not my primary language. If you need any extra piece of code, I can add it.
You need to make sure you export the tween jar files in your Build Path. For Eclipse, you can Right-click on the project, choose "Build Path" > "Configure Build Path", go to the "Order and Export" tab on the right side, and make sure that the tween jar files are checked in the list there.

Categories