How to Correctly Get Image from 'Resources' Folder in Netbeans

How to correctly get image from 'Resources' folder in NetBeans

Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image.
In one of my tries i use

    String pathToImageSortBy = "resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

But correct way was use name of my project in path to resource

String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

Loading resources like images while running project distributed as JAR archive

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

How to save image into resource folder java swing

private void jbtnSubmitActionPerformed(java.awt.event.ActionEvent evt) {                                           
// TODO add your handling code here:
String itemname = jtxtItemName.getText();
String category = jcboCategory.getSelectedItem().toString();
String description = jtxtAreaDescription.getText();
String reservedPrice = jtxtReservedPrice.getText();
String image =filename;

if (itemname.isEmpty() || category.isEmpty() || description.isEmpty() || reservedPrice.isEmpty() || image.isEmpty()) {
JOptionPane.showMessageDialog(null, "All fields are required.");
} else {
Item item = new Item(category, description, reservedPrice, itemname, image);
try {
int i = itemdao.createItem(item);
if(i> 0 ){
File sourceFile = new File(path);
File destinationFile = new File("resources/Image/"+ filename);
BufferedReader reader;
PrintWriter writer;
try {
reader = new BufferedReader(new FileReader(sourceFile));
writer = new PrintWriter(new FileWriter(destinationFile));
reader.close();
writer.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Failed to save Image");
}
//Paths.get(resource.toURI()).toFile();
JOptionPane.showMessageDialog(null, "Successfully saved item");
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
}

JavaFX Image from resources folder

Resources

The Class#getResource(String) and related API are used for locating resources relative to the class path and/or module path. When using Class to get a resource you can pass an absolute name or a relative name. An absolute name will locate the resource relative to the root of the class path/module path; an absolute name starts with a /. A relative name will locate the resource relative to the location of the Class; a relative name does not start with a leading /.

In a typical Maven/Gradle project structure, the src/main/java and src/main/resources are roots of the class path/module path. This means all resource names are relative to those directories. It's slightly more complicated than that because the files under those directories are moved to the target/build directory and it's that location that's put on the class path/module path, but for all intents and purposes consider the source directories as the root. There's a reason a get-resource API exists in the first place, to provide an application-location-independent way of obtaining resources.


Issues in Your Code

From your question I gather your project structure looks something like:

<project-dir>
|--src/
|--main/
|--java/
|--resources/
|--images/
|--image.png

And you're calling your method with an Object and a resource name of image.png. The problem here is that, since you're passing a relative name, the resource is located relative to the Class of the passed Object (i.e. context). I doubt your class is located in a package named images which means the resource will not be found relative to said class. You need to pass an absolute name: /images/image.png.

The other problem is your use of URL#getPath(). The URL you obtain from Class#getResource(String) will, if the resource were to be found, look something like this:

file:/path/to/gradle/project/build/resources/main/images/image.png

But the result of URL#getPath() will give you:

/path/to/gradle/project/build/resources/main/images/image.png

This causes a problem due to the way Image works. From the documentation:

All URLs supported by URL can be passed to the constructor. If the passed string is not a valid URL, but a path instead, the Image is searched on the classpath in that case.

Notice the second sentence. If the passed URL does not have a scheme then it's interpreted as a resource name and the Image will locate the image file relative to the classpath. In other words, since you're passing the value of URL#getPath() to the Image constructor it searches for the resource image.png in the package path.to.gradle.project.build.resources.main.images. That package does not exist. You should be passing the URL as-is to the Image constructor via URL#toString() or URL#toExternalForm().


Solution

If you're going to use the URL returned by Class#getResource(String) to load the Image then no matter what you need to use URL#toString() or URL#toExternalForm() instead of URL#getPath().

public static Image createImage(Object context, String resourceName) {
URL _url = context.getClass().getResource(resourceName);
return new Image(_url.toExternalForm());
}

Then you have at least two options:

  1. Pass the absolute resource name (i.e. "/images/image.png") to your #createImage(Object,String) method since the image.png resource is not in the same package as the passed Object (i.e. context).

  2. Move the resource to the same package as the class of the passed in Object (i.e. context). For instance, if the context object's class is com.foo.MyObject then place the resource under src/main/resources/com/foo and it will be in the same package as MyObject. This will allow you to continue passing the relative resource name.

Of course, as noted by the documentation of Image you can pass a scheme-less URL and it's interpreted as a resource name. In other words, you could do:

Image image = new Image("images/image.png");

And that should work. A note of caution, however: When using modules the above will only work if the resource-containing package is opens unconditionally or if the module itself is open.

How to access resource files in Netbeans (Java)?

As per the netbeans directory project structure, you need to create one resources directory. Then put your files there in resource directory.

Please update your code like below.

Put your file under /resources/, then use it like below.

ProcessBuilder pb= new ProcessBuilder("resources/ProcessImg.m");
Path data_file = Paths.get("resources/data.txt")

Load image from a file inside a project folder

Set the assets directory as a resource directory and then load the image as a resource from the location "/drawIcon.png":

URL url = getClass().getResource("/drawIcon.png");
Image image = ImageIO.read(url);

In case you want to create a javafx Image:

Image image = new Image("/drawIcon.png");

In this case, also, mark that folder as resource folder.

More info here: https://docs.oracle.com/javafx/2/api/javafx/scene/image/Image.html

Netbeans Designer and .form files in resources folder

What is the .form file

From faq:

The .form file is an XML file that the visual editor uses to store the information about the GUI form. It is much more reliable than reading the information from the source code. You do not need to distribute the .form file with your application; it's only used by the IDE. However, if you want to open your form again in the form editor, you should keep the file

Directory Layout

Indeed the standard directory layout for a maven project consists of src/main/java for java files and src/main/resources for resources. But it is only true for maven projects.

The ant-based project uses a different layout and usually places properties files and other files withing source directories but could use any custom locations for resources including sub-directories within a package.

Use a different folder for .forms files

Unfortunately, it's impossible to separate them from the relevant so caled "brother" files, see below. They are too tightly coupled together. For example, if you look at the project tree view NetBeans hides the .form files if there are relevant java files within the same directory.

Let's see the source code, precisely a method findPrimaryFile that is used for finding a primary file:

  protected FileObject findPrimaryFile(FileObject fo) {
if (fo.isFolder()) return null;
String ext = fo.getExt();
if (ext.equals(FORM_EXTENSION))
return FileUtil.findBrother(fo, JAVA_EXTENSION);

FileObject javaFile = findJavaPrimaryFile(fo);
return javaFile != null
&& FileUtil.findBrother(javaFile, FORM_EXTENSION) != null ?
javaFile : null;
}

It calls findBrother method that looks for appropriate .form or java files and it always looks for the "brother" file within the same directory:

public static FileObject findBrother(FileObject fo, String ext) {
if (fo == null) {
return null;
}

FileObject parent = fo.getParent();

if (parent == null) {
return null;
}
return parent.getFileObject(fo.getName(), ext);
}


Related Topics



Leave a reply



Submit