Exception in thread - java

public class Intro extends JFrame implements ActionListener {
ImageIcon pic = new ImageIcon(this.getClass().getResource("cars-games.jpg"));
JLabel l1 = new JLabel();
Image car = pic.getImage();
public static void main (String[]args){
Intro i = new Intro();
i.show();
}
}
Its giving me this error:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at Intro.<init>(Intro.java:15)
at Intro.main(Intro.java:58)
Can anyone help plz.

Your resource is null, and ImageIcons cannot be constructed with null parameters.
Make sure you've entered the correct path to "cars-games.jpg".

I think it's not able to read your image file and hence the issue.
Try using classLoader as :
ImageIcon pic = new ImageIcon(getClass().getClassLoader()
.getResource("cars-games.jpg"));
If still you get the same issue then make sure that cars-games.jpg is available in root of your class loader location.

I was getting this issue a lot at the beginning of development for my java game project for this semester. This generally means that the resource that you are trying to access is not able to be found (i.e. Nullpointerexception). What I did to make everything much easier was to just make a separate folder in your java project called images (especially if you are using multiple images in this project). Then you can just call new ImageIcon with your directory. Makes things a lot easier in the end.
As stated earlier, getClassLoader() works as well!

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

GetClass issue in Java Application Setting Icon

I am trying to do the simple activity of setting the Application Icon in a java application. I have many working examples with me but in this instance it fails. Please help I have tried a) b) c) marked in the code. a) Gives a error hint 'Non-static getClass cannot be referenced from a static context' So I tried b) and c). In both, the program runs, but NO Icon is set, NO errors. (I have put the same image in different paths for test purpose)
private static void createAndShowGUI() {
myFrame = new MyDynamic();
myFrame.setTitle( "Sunsong Public School : Home" );
a)myFrame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("../Images/Sudan.png")));
b)myFrame.setIconImage(ImageIO.read(new File("../Images/Sudan.png")));
c)Image icoon = Toolkit.getDefaultToolkit().getImage("Sudan.png"
Got the solution from some other source. The funny thing is I have dozens of working Applications with Icon. In all of them I am using the Toolkit-getclass-getresources. But in this case I was tinkering with an old code, and stuck inside a static block. From the static context Calling toolkits non-static getClass is NOT working. Had tried hundreds of examples from the net in the last 20 or so hours. Java IO also NOT working complains cannot 'read from file'.
This is the one Finally worked..
ImageIcon icon = new ImageIcon(ClassLoader.getSystemResource("Sudan.png"));
Image img = icon.getImage();
myFrame.setIconImage(img); // frame is a JFrame

Having issues loading an image from a sprite sheet, am i loading the sprite sheet correctly? [duplicate]

I've been making a 2D game with my buddy and I've been learning a lot about some basic game dev concepts through some Youtube tutorials. One of the things I was learning about is sprites (for those that don't know, 2D images to render to the screen) and how to use them in my game. I've been using ImageIO.read(this.class.getResource(pathToMySprite)) but it seems that getResource() is returning null for some reason.
I've been screwing around with the path a little, adding "/" in front of it, removing "/", putting the user.dir property to see if it needed the whole path, and I'm still getting the same error.
TILE_TEXTURES(System.getProperty("user.dir") + "/textures/tile.png");
//ENTITY_TEXTURES("/textures/entity.png");
private BufferedImage img;
private SpriteSheet(String path) {
System.out.println(System.getProperty("user.dir"));
try {
//TODO: Fix this error, don't know what's wrong.
img = ImageIO.read(SpriteSheet.class.getResource(path)); // error here!!!
} catch (IOException e) {
e.printStackTrace();
}
}
public BufferedImage getImage() {
return img;
}
Any and all help is appreciated.
I haven't been commenting the code (I usually do that when I get to place where I can sit back and be happy with what I've finished) but it's a pretty small class so I think you guys will be able to understand what's going on just fine.
The folder that holds the image IS in the class path of my project.
I've also included the error:
Exception in thread "Thread-2" java.lang.ExceptionInInitializerError
at com.brickbattle.client.src.gui.Sprite.<clinit>(Sprite.java:7)
at com.brickbattle.client.src.objs.Tile.<init>(Tile.java:67)
at com.brickbattle.client.src.objs.Player.initPlayerNum(Player.java:19)
at com.brickbattle.client.src.util.BrickBattle.init(BrickBattle.java:114)
at com.brickbattle.client.src.util.BrickBattle.run(BrickBattle.java:85)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: input == null! //HERE IS ERROR
at javax.imageio.ImageIO.read(Unknown Source)
at com.brickbattle.client.src.gui.SpriteSheet.<init>(SpriteSheet.java:17)
at com.brickbattle.client.src.gui.SpriteSheet.<clinit>(SpriteSheet.java:8)
Thanks again!
This problem is basically unrelated to ImageIO, but rather how Class/ClassLoader.getResource or getResourceAsStream works.
For an explanation, see this answer.
In any case, these ways of obtaining a resource will only be able to read from classpath (ie. user.dir will never help here).
This should work:
ImageIO.read(getClass().getResource("/path/to/resource"));
Where the path is relative to the root of the classpath (specified by the leading /).
If your resources are not on the classpath, simply use:
ImageIO.read(new File("path/to/resource");
Where the path is relative to the directory your application was launched from.

Trying to load FXML file to custom-made JavaFX Game class (made by professor)

I'm beyond confused, and I have no idea where to even begin with this project and it's due tomorrow. We went over literally one slide of JavaFX and they assign us a project - make an entire game, Breakout or Space Invader. I wish I was exaggerating.
Here's my current problem: I'm trying to use an FXML file in my Driver class but the Game class he provided us doesn't extend Pane, which is the only way I know to get an FXML resource.
Here's some of the code:
public class Driver extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
Game game = new Breakout(primaryStage);
try {
game = FXMLLoader.load(getClass().getResource("BreakoutFXML.fxml"));
} catch (IOException e) {
System.out.println(e);
System.exit(1);
} // try
primaryStage.setTitle(game.getTitle());
primaryStage.setScene(game.getScene());
primaryStage.show();
game.run();
} // start
I get this run-time error:
Caused by: java.lang.ClassCastException: javafx.scene.layout.Pane cannot be cast to com.michaelcotterell.game.Game
at cs1302.fxgame.Driver.start(Driver.java:19)
Means (I think) that I can't use this method of acquiring an FXML file, so what am I supposed to do?
Here's the link to his documentation for the Game class, should be helpful.
I realize this question has been asked a lot, but I haven't been able to find anything using anything other than the standard Pane/Scene classes to get the FXML file. If it's an easy fix - awesome! Sorry for being such a noob.
Well try one of these:
Pane myPane = FXMLLoader.load(getClass().getResource("BreakoutFXML.fxml"));
// 1
game.getScene().getRoot().add(myPane);
// 2
game.getScene().setRoot(myPane);
// 3
game.getStage().setScene(new Scene(myPane));

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.

Categories

Resources