Cannot create image from getResourceAsStream() in JavaFX projects - java

I cannot create an image in any of my JavaFX projects using the following kind of code:
final String url = "line.jpg";
Image image = new Image(Config.class.getResourceAsStream(url));
because there is always a null pointer exception pointing to the second line. Obviously, I have checked that the image file is in the correct directory. I have tried example programs, some directly copied from these boards, but these also fail for the same reason.
I suspect I lack a resource in Netbeans or JavaFX but I can't figure out what is missing.

The only workaround appears to be to include the image file in a css stylesheet and link it to the program by setting the gui components id like this:
Button homeButton = new Button();
homeButton.setId("homebutton");
In the stylesheet there is:
#homebutton {
-fx-background-image: url("images/homebtn.jpg");
-fx-pref-width: 30;
-fx-pref-height: 30;
}
Its not ideal being forced into this solution and Swing seems far better at dealing with image files. I assume a bug in JavaFX that always causes the following to fail:
Image image = new Image(Config.class.getResourceAsStream(url));

Related

Java getResourceAsStream NullpointerException when loading image for JavaFX ImageView

I have the following project setup (Maven Project):
project setup
And the absolute path:
C:\Users\jenny\IdeaProjects\gameapp\client\src\main\resources\images\game\black_market.png
This code throws a Nullpointerexception:
private void setUpImage(ImageView image){
Platform.runLater(()->{
var url = getClass().getResourceAsStream("images/game/black_market.png");
System.out.println(url.toString());
Image img = new Image(url);
image.setImage(img);
});
}
It's probably because the filepath is incorrect but I don't really know how to fix it on my own. I've tried for the last 2-3 hours researching similar problems on Stackoverflow.
The ImageView that gets passed on this function is a reference to an ImageView. My function should load the image and put it into the passed ImageView. To be honest, I don't actually know if that will work since Java is pass by value.
why setImage() doesn't change my ImgView in JavaFx?
This question fixed it. I've noticed that the #FXML annotations were missing. Adding them fixed the entire problem.
#FXML
private void setUpImage(ImageView image){
Platform.runLater(()->{
Image img = new Image("/images/game/black_market.png");
image.setImage(img);
});
}

Why does my ImageView work on Windows but not on Mac

Here is the simple code for javafx in intellij:
Image image = new Image(url);
ImageView imageView = new ImageView(image);
movieBox.getChildren().add(imageView);
//checking
System.out.println(imageView.getImage().getUrl());
Textfield tx = new Textfield();
tx.setText("hi");
movieBox.getChildren().add(tx);
I copied the project over to intellij on my mac and everything works accept the images won't show. Here are the things I tried:
Checking that the URL is valid by printing out the imageview image url. It prints out a valid URL of an image i can open in my browswer
Adding a random textfield to the movieBox (a flowpane object) to make sure it works. And it does.
There shouldn't be any error in the code because it works in my windows intellij. It seems like a problem with the environment, but I haven't even got a clue how should i approach this problem. Any sort of advice will be nice, thanks!
Try downloading the image and using the path to the image on your disk, if it works then the problem will be with the url, otherwise its with the ImageView. If the problem is with the URL, post the one you are trying to use so the community can test it, and try another URL.
P.S. If you aren't manipulating the image you can just pass the path/url directly top the ImageView constructor.
public ImageView(String url)
Allocates a new ImageView object with image loaded from the specified URL.
The new ImageView(url) has the same effect as new ImageView(new Image(url)).

How should I use getResource()?

I use getResource() to load the image, but I get nullpointer exception. Also I tried to use css but I get nothing.
My code for label:
Image mine = new Image(getClass().getResourceAsStream("bomb3.png"));
ImageView im = new ImageView(mine);
Label label = new Label();
label.setGraphic(im);
And for button:
btn.setStyle("-fx-background-image: url('flag.png')");
This code is located in Painter class.
My file tree:
If you use getClass().getResourceAsStream("bomb3.png") java search in the packetof your class. So if your class is Game, your resource must be in the packet: com.name.minesweeperClasses
Image mine = new Image(getClass().getResourceAsStream("bomb3.png"));
here path of bomb3.png is incorrect
Please mention the relative path :-
./resources/boob3.png

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);

After buiding java app, some GUI components does not work properly, but during IDE tests everything is fine. Why?

I am working on GUI java project which contains FileChooser(combined with JLabel it becomes ImageChooser) and JTextArea (inside of JScrollPane). Both of these components are inside of JPanel.
When ever I ran it inside of IntelliJ Idea (version 2017.2.4)everything works fine:
UI when executed from IDE
But if I build Artifacts and create .jar file, then image inside of JLabel is not initialized and the size(height) of JTextArea becomes minimal(though minimal value is set to 200):
IU when executed from .jar file
I suspect that ImageIcon cannot be initialized due to relative path I provide:
...
imagePath = "src/main/resources/" + item.getImageName();
//item.getImageName() returns a proper image name, tested with
//System.out.println() and there is a proper image in that folder.
ImageIcon img = new ImageIcon(imagePath);
img = ImageManager.resize(img);
...
//Resize function in ImageManager class
public static ImageIcon resize(ImageIcon imageIcon, int size){
return resize(imageIcon, size, size);
}
public static ImageIcon resize(ImageIcon icon){
return resize(icon, defaultSize);
}
However, I've tried options with relative path like main/resources/ and /main/resources/ , but none of them worked both in IDE and .jar executable.
Is it a problem with a path?
If yes, why does it affect JTextArea's size?
P.S.
JTextArea's size becomes normal if there is an image in JLabel.
You are right, the way you fetch resources is problematic in a jar.
The way you should access them:
ImageIcon img = new ImageIcon(this.getClass().getClassLoader().getResource(item.getImageName()));
This method supports relative paths. Just make sure your src/main/resources directory is properly marked as a 'Resource Root' in IntelliJ IDEA.

Categories

Resources