how to show images with a relative path on a JavaFX application? - java

I'm creating a JavaFX application that needs to show an image, my currently way to do that is this:
ImageView icon=new ImageView(new Image("file:///C:/Users/MMJon/eclipse-workspace/Pumaguia/src/vista/resources/rutas.png"));
i've tried to do it like this
ImageView icon=new ImageView(new Image(this.getClass().getResource("resources/rutas.png").toExternalForm()));
but it throws a Null Pointer exception. How can i do what i need?
Here's an image of the console
and here's an image of my project's structure
My main class is "pumaguia" and the class that shows the image is in "pestanas" package, and the folder that contains the image is "resources".
UPDATE:
I've tried to compile on ubuntu's command line and this was what i get. Hope it helps.

Going to assume you are using JDK 8 and above. The path must be relative and be preceded with the appropriate platform path separator.
Define an ImageProvider to ensure you handle the absence of the image correctly. Note that I use a class reference to establish the resource path.
public class ImageProvider {
private static ImageProvider imageSingleton;
private Image image = null;
private static final java.util.logging.Logger LOGGER = LogManager.getLogManager().getLogger("MyApp");
private ImageProvider(String imageStr) {
try {
image = new Image(ImageProvider.class.getResource(imageStr).toURI().toString());
} catch (URISyntaxException ex) {
LOGGER.log(Level.SEVERE, "Cannot fine image.", ex);
}
}
/**
* Returns an Image if possible.
* #param imageStr the relative path preceded by the appropriate platform path separator.
* #return
*/
public static Image getImage(String imageStr) {
return Optional.ofNullable(imageSingleton).orElseGet(() -> imageSingleton = new ImageProvider(imageStr)).image;
}
You can then use;
ImageProvider.getImage("/img/myImage.png")

Related

Open a File in default File explorer and highlight it using JavaFX or plain Java

I wish to do what the title says.
Part Solution:
For example in Windows you can use the code below to open a file in the default explorer and highlight it.
(although it needs modification for files containing spaces):
/**
* Opens the file with the System default file explorer.
*
* #param path the path
*/
public static void openFileLocation(String path) {
if (InfoTool.osName.toLowerCase().contains("win")) {
try {
Runtime.getRuntime().exec("explorer.exe /select," + path);
} catch (IOException ex) {
Main.logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
Useful Links:
Links which are similar but no way dublicates or not answered:
How to use java code to open Windows file explorer and highlight the specified file?
Open a folder in explorer using Java
How can I open the default system browser from a java fx application?
More explanation:
Is there a way to do it using JavaFX ?
If not at least i need a link or some way to make the app system
independence.I mean i don't know the default explorer for every OS
that the application is going to work , i need a link or help doing that.
Do i need to write a ton of code to do this?
Is out there any library for doing that?
Do Java9 support that?
Finally:
It is very strange that for so common things i can't find answers and libraries .
Example of highlighted or selected in Windows 10:
Windows
Runtime.getRuntime().exec("explorer /select, <file path>")
Linux
Runtime.getRuntime().exec("xdg-open <file path>");
MacOS
Runtime.getRuntime().exec("open -R <file path>");
Since Java 9 it's possible with the new method browseFileDirectory, so your method would state:
import java.awt.Desktop;
import java.io.File;
...
/**
* Opens the file with the System default file explorer.
*
* #param path the path
*/
public static void openFileLocation(String path) {
Desktop.getDesktop().browseFileDirectory(new File(path));
}
For more information, refer to the javadoc:
https://docs.oracle.com/javase/10/docs/api/java/awt/Desktop.html#browseFileDirectory(java.io.File)
The following is a partial answer showing you how to open the system folder you desire, but not how to highlight a specific file since I do not believe it is possible to highlight a file in a system folder, because that is probably a system OS function that cannot be accessed by Java.
This is written in Javafx code
In your Main class make a variable for Hostservices. Note that "yourFileLocation" is the address of the folder to the file, and SettsBtn is a button that exists somewhere which the user clicks to execute the code:
public class Main extends Application{
static HostServices Host; //<-- sort of a global variable
//some code here to make your GUI
public Main() {
//more code here to initialize things
}
public void start(Stage primaryStage) throws Exception {
//some code here to set the stage
//This code here opens the file explorer
SettsBtn.setOnMouseClicked(e-> {
Path partPath = Paths.get("yourFileLocation");
Host = getHostServices();
Host.showDocument(partPath.toUri().toString());
});
}
}
Note that you could directly open the file by making a string to the file location and the file name with its extension, such as:
Path partPath = Paths.get("yourFileLocation"+"\\"+"yourFileName.ext");
As of Java 17 the Desktop::browseFileDirectory method is still not supported on Windows 10 or later.
The historic reason is that Apple originally implemented these native Desktop integration features for Mac OS X in the com.apple.eawt package back when Apple itself was still maintaining the JDK for Mac OS X. All of that was ported into java.awt.Desktop for Java 9 as per JEP 272: Platform-Specific Desktop Features and so I guess some of these features are still only implemented for Mac OS X to this day.
Fortunately, Windows 10 does have a SHOpenFolderAndSelectItems function that we can call via JNA like so:
public interface Shell32 extends com.sun.jna.platform.win32.Shell32 {
Shell32 INSTANCE = Native.load("shell32", Shell32.class, W32APIOptions.DEFAULT_OPTIONS);
HRESULT SHParseDisplayName(WString pszName, Pointer pbc, PointerByReference ppidl, WinDef.ULONG sfgaoIn, Pointer psfgaoOut);
HRESULT SHOpenFolderAndSelectItems(Pointer pidlFolder, WinDef.UINT cidl, Pointer apidl, WinDef.DWORD dwFlags);
}
public class Shell32Util extends com.sun.jna.platform.win32.Shell32Util {
public static Pointer SHParseDisplayName(File file) {
try {
PointerByReference ppidl = new PointerByReference();
// canonicalize file path for Win32 API
HRESULT hres = Shell32.INSTANCE.SHParseDisplayName(new WString(file.getCanonicalPath()), null, ppidl, new WinDef.ULONG(0), null);
if (W32Errors.FAILED(hres)) {
throw new Win32Exception(hres);
}
return ppidl.getValue();
} catch (Exception e) {
throw new InvalidPathException(file.getPath(), e.getMessage());
}
}
public static void SHOpenFolderAndSelectItems(File file) {
Pointer pidlFolder = SHParseDisplayName(file);
try {
HRESULT hres = Shell32.INSTANCE.SHOpenFolderAndSelectItems(pidlFolder, new WinDef.UINT(0), null, new WinDef.DWORD(0));
if (W32Errors.FAILED(hres)) {
throw new Win32Exception(hres);
}
} catch (Exception e) {
throw new InvalidPathException(file.getPath(), e.getMessage());
}
}
}

System Tray image not loading java

I have a program which when runs displays an icon in system tray. i am using the below code to display an icon in system tray area:
public static void showTrayIcon() {
if (java.awt.SystemTray.isSupported()) {
st = java.awt.SystemTray.getSystemTray();
image = Toolkit.getDefaultToolkit().getImage(PongeeUtil.class.getClass().getResource("export.png"));
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Hello");
}
};
PopupMenu popup = new PopupMenu();
MenuItem defaultItem = new MenuItem("sdf");
defaultItem.addActionListener(listener);
popup.add(defaultItem);
trayIcon = new TrayIcon(image, "Tray Demo", popup);
trayIcon.addActionListener(listener);
try {
st.add(trayIcon);
} catch (AWTException e) {
System.err.println(e);
}
}
}
When i call this method in my main() i got something in my system tray but icon is missing. i think image is not able to load. image is in the same package where my java files resides.
What am i doing wrong here ?
image is in the same package where my java files are
If you take a look at the JavaDocs for Toolkit#getImage you will find that it says...
Returns an image which gets pixel data from the specified file
This is important. You should also know that getImage loads the physical image in a background thread, which means if it fails to load the image, it will do so silently...
Okay. The core problem is, once the image is placed within the context of the application (with the class files), it becomes, whats commonly known as, an embedded resource.
These resources can not be loaded via any means that requires access to a file on the file system.
Instead, you need to use Class#getResource or Class#getResourceAsStream to load them, for example
image = Toolkit.getDefaultToolkit().getImage(YourClass.class.getResource("/package/path/to/classes/export.png"));
Or more preferabbly...
BufferedImage img = ImageIO.read(YourClass.class.getResource("/package/path/to/classes/export.png"));
image = new ImageIcon(img);
ImageIO will throw an IOException when it can't load the image for some reason, which gives you more diagnostic information to fix problems
nb:
YourClass is you class which contains the showTrayIcon method...
/package/path/to/classes is the package name under which the image is stored...

Change the default Java icon [duplicate]

I'm using NetBeans, trying to change the familiar Java coffee cup icon to a png file that I have saved in a resources directory in the jar file. I've found many different web pages that claim they have a solution, but so far none of them work.
Here's what I have at the moment (leaving out the try-catch block):
URL url = new URL("com/xyz/resources/camera.png");
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
getFrame().setIconImage(img);
The class that contains this code is in the com.xyz package, if that makes any difference. That class also extends JFrame. This code is throwing a MalformedUrlException on the first line.
Anyone have a solution that works?
java.net.URL url = ClassLoader.getSystemResource("com/xyz/resources/camera.png");
May or may not require a '/' at the front of the path.
You can simply go Netbeans, in the design view, go to JFrame property, choose icon image property, Choose Set Form's iconImage property using: "Custom code" and then in the Form.SetIconImage() function put the following code:
Toolkit.getDefaultToolkit().getImage(name_of_your_JFrame.class.getResource("image.png"))
Do not forget to import:
import java.awt.Toolkit;
in the source code!
Or place the image in a location relative to a class and you don't need all that package/path info in the string itself.
com.xyz.SomeClassInThisPackage.class.getResource( "resources/camera.png" );
That way if you move the class to a different package, you dont have to find all the strings, you just move the class and its resources directory.
Try This write after
initcomponents();
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("Your image address")));
/** Creates new form Java Program1*/
public Java Program1()
Image im = null;
try {
im = ImageIO.read(getClass().getResource("/image location"));
} catch (IOException ex) {
Logger.getLogger(chat.class.getName()).log(Level.SEVERE, null, ex);
}
setIconImage(im);
This is what I used in the GUI in netbeans and it worked perfectly
In a class that extends a javax.swing.JFrame use method setIconImage.
this.setIconImage(new ImageIcon(getClass().getResource("/resource/icon.png")).getImage());
You should define icons of various size, Windows and Linux distros like Ubuntu use different icons in Taskbar and Alt-Tab.
public static final URL ICON16 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug16.png");
public static final URL ICON32 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug32.png");
public static final URL ICON96 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug96.png");
List<Image> images = new ArrayList<>();
try {
images.add(ImageIO.read(HelperUi.ICON96));
images.add(ImageIO.read(HelperUi.ICON32));
images.add(ImageIO.read(HelperUi.ICON16));
} catch (IOException e) {
LOGGER.error(e, e);
}
// Define a small and large app icon
this.setIconImages(images);
You can try this one, it works just fine :
` ImageIcon icon = new ImageIcon(".//Ressources//User_50.png");
this.setIconImage(icon.getImage());`
inside frame constructor
try{
setIconImage(ImageIO.read(new File("./images/icon.png")));
}
catch (Exception ex){
//do something
}
Example:
URL imageURL = this.getClass().getClassLoader().getResource("Gui/icon/report-go-icon.png");
ImageIcon iChing = new ImageIcon("C:\\Users\\RrezartP\\Documents\\NetBeansProjects\\Inventari\\src\\Gui\\icon\\report-go-icon.png");
btnReport.setIcon(iChing);
System.out.println(imageURL);

ImageIcon lost after creating a runnable JAR file

The project runs fine when I click play in Eclipse but after I created the runnable JAR file, The ImageIcon for the button is gone.
The images are stored within the src folder, uder a subfolder images.
I created the image icon as
Icon playIcon = (Icon) new ImageIcon("src/images/play.png");
Although I am using a relative path, the button does not display images, How do I get the images even in the JAR file?
Update after Nikolay Kuznetsov's answer
I ended up creating a very unstructured monolithic code for screen recorder and now it is slightly difficult to implement what he said.
I was wondering if there is a way like creating a class or interface that will contain all these resources.
For example:
public class embeddedResources {
public static Icon blackCursor;
public static Icon whiteCursor;
...
...
}
Then all I have to do is import these statics and in my main ScreenRecorder class,
this.blackCursor = embeddedResources.blackCorsor;
I am using this method to read image into BufferedImage where IconManager is class where it is defined.
private static BufferedImage readBufferedImage (String imagePath) {
try {
InputStream is = IconManager.class.getClassLoader().getResourceAsStream(imagePath);
BufferedImage bimage = ImageIO.read(is);
is.close();
return bimage;
} catch (Exception e) {
return null;
}
}
I had the same problem.
Try to make you JAR file and add your images to an extern folder.
So you have a folder "Game" in this folder are the folder for your images called "images" or so and your jar file.
If you now edit you folder path to "../images/play.png" it should work.

Java: When a program is .jar 'ed, it no longer reads the images in the jar file?

I need it to run without having the files exported to the computer.
At the moment, my code for storing the images is:
ImageIcon icon = new ImageIcon("images\\images2.gif");
It can't just be an image since I'm adding it to a JLabel.
When I jar the entire program, it stores the image files in the jar.
When I go to run the actual problem, there are no images.
Again, I can't just leave the .jar in a folder with the images already. It has to work on a separate computer, by itself.
You'll want to get the image via the system class loader:
URL url = ClassLoader.getSystemClassLoader().getResource("images/images2.gif");
Icon icon = new ImageIcon(url)
images is at the root of the classpath.
Note that the Java runtime will translate the separator (/) to the OS specific separator (\ for Windows).
You need to access those files through class-loader... Something like this:
InputStream is = this.getClass().getClassloader().getResourceAsStream("images/image.ico");
HTH
UPD: note, that this will work both with JARed package and with plain directory structure.
The basic issue is that the File class only knows how to work with what the underlying operating system consider a file, and a whole one.
A jar file is essentially a zip file with some extra information so you cannot use File's with that. Instead Java provides the "resource" concept which roughly translates to "a chunk of bytes or characters which we don't care where is, as long as we have them when we need them". You can ask the class loader for any resource in the class path - which is what you want here - or access it through an URL.
Try this:
ImageIcon icon = new ImageIcon(this.getClass().getClassloader().getResource("images/images2.gif"));
if that doesn't work, replace this.getClass().getClassloader() with MyClass.class where MyClass is the name of your class.
I remember having to edit this slightly to make it work in Eclipse, but when you deploy it, it works like a charm.
Edit: To make it work in Eclipse, you may need to change it to:
ImageIcon icon = new ImageIcon(this.getClass().getClassloader().getResource("bin/images/images2.gif"));
If that doesn't work, do the standard, replace this.getClass().getClassloader() with MyClass.class. If it still doesn't work, try replacing "bin" with "src". Try jar'ing it with the first way and see what happens.
Here is a convenient utility class that can be used for loading image resources. The log4j logger can be removed of changed to whatever is more appropriate.
public class ResourceLoader {
private static final Logger logger = Logger.getLogger(ResourceLoader.class);
public static Image getImage(final String pathAndFileName) {
try {
return Toolkit.getDefaultToolkit().getImage(getURL(pathAndFileName));
} catch (final Exception e) {
logger.error(e.getMessage());
return null;
}
}
public static ImageIcon getIcon(final String pathAndFileName) {
try {
return new ImageIcon(getImage(pathAndFileName));
} catch (final Exception e) {
logger.error(e.getMessage());
return null;
}
}
public static URL getURL(final String pathAndFileName) {
return Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
}
}
I suppose images2.gif is inside the package images
URL imageurl = getClass().getResource("/images/images2.gif");
Image myPicture = Toolkit.getDefaultToolkit().getImage(imageurl);
JLabel piclabel = new JLabel(new ImageIcon( myPicture ));
piclabel.setBounds(0,0,myPicture.getWidth(null),myPicture.getHeight(null));
If your images are located this way.
Then this should do the job.
private String imageLocation "/images/images2.png";
private ImageIcon getImageIconFromJar(String imageLocation)
{
try
{
BufferedImage bi = ImageIO.read(this.getClass().getResource(imageLocation));
ImageIcon ic = new ImageIcon(bi);
return ic;
} catch (IOException e)
{
System.out.println("Error: "+e);
}
return null;
}

Categories