I have search all over the web but could not find answer to this question:
I need to debug the functioning of an application that changes the SplashScreen based on the module you are accessing.
I do know that the code:
SplashScreen splash = SplashScreen.getSplashScreen();
Can be used to get the instance when you pass either:
Splash from command line: java -splash:path/image.gif ClassFile
Splash image in manifest: splashscreen-image: img/SplashNomina.gif
Still when I tried to run the application by passing the -splash value from VM args in Eclipse it did not work.
Is it actually possible as SplashScreen.getSplashScreen() is always NULL.
I have been trying passing without success:
-splash:image.gif
-Dsplash=image.gif
Right now I see lots of limitations in this Splash api, as it is always required to have a parameter being passed. I think it would be much more flexible to be able to just pass the parameter at runtime :(
Any help woult be really appreciated!
OK, this has bitten me too.
I built a runnable jar
with manifest entry
SplashScreen-Image: MyGraphic.jpg
and it works as it's supposed to.
From Eclipse, specifying the VM arg as
-splash:MyGraphic.jpg
no such luck
SplashScreen.getSplashScreen() returns null.
The reason for this is the brain-dead implementation of SplashScreen.getSplashScreen() in the JDK (at least 1.6). I think. It's kind of hard to tell without getting into what the native code is doing. But, here is this method from java.awt.SplashScreen. I'm not sure if it's called but studying it did provide me with the essential clue I needed to get this working in Eclipse:
public synchronized URL getImageURL() throws IllegalStateException {
checkVisible();
if (imageURL == null) {
try {
String fileName = _getImageFileName(splashPtr);
String jarName = _getImageJarName(splashPtr);
if (fileName != null) {
if (jarName != null) {
imageURL = new URL("jar:"+(new File(jarName).toURL().toString())+"!/"+fileName);
} else {
imageURL = new File(fileName).toURL();
}
}
}
catch(java.net.MalformedURLException e) {
// we'll just return null in this case
}
}
return imageURL;
}
Note that in the case of a file (i.e. command-line rather than jar launch) it's not doing a getResource() to get the URL but opening a file relative to the CWD. Since Eclipse run configurations default to running from the root of the project, the answer is to specify the path as a relative path and not to expect a classpath lookup.
Therefore, since I am building with maven, my image is located at src/main/resources/MyGraphic.jpg. Specifying this as the command line parameter: i.e.
-splash:src/main/resources/MyGraphic.jpg
allows it to work in Eclipse (or, I guess, any command line)
I'm not sure WHY this is, since the getImageURL method is NOT called by getSplashScreen() but it DOES work.
To me this is kind of brain-dead on the part of Sun/Oracle. They could have easily done a classpath lookup with something like
imageURL = getResource(filename) but they did not.
The short answer is that the Splash Screen command line syntax refers to a filename relative to the current working direrctory, not relative to the classpath.
I'm answering 3 years later but I had the same problem and I tried to resolve.
I found the solution, and I think it would be useful to everybody.
You have to create a launch configuration, specifying in the VM arguments the parameter -splash:image.gif. This parameter refers to the root directory of the project (not /bin or /src). So you have to put your image in the same level as /bin and /src (or you can specify a different path in the -splash option).
When you export the runnable JAR from 'export' specifying the launch configuration you created before, it says 'can't include VM arguments, you have to specify from command line' (and it doesn't include your image.gif in the root).
So if you want to have a runnable jar with your splash image, you can refer to another topic on stackoverflow which i'm not finding anymore. Someone answered that the best solution is FatJar. You can proceed as follows: export > other > fat jar exporter. Tick 'select manifest file', specifying a MANIFEST.MF containing 'SplashScreen-Image: splash.gif' (if you don't know how to create, deselect this checkbox, create a jar with the default one, modify the one created and include it). In the next page of the exportation, be sure to include your images in the jar with the 'add dir' button (it includes the content of the directory specified to the root directory of the project, so pay attention with the directory in the manifest).
It worked for me.
So if you want to run with eclipse, add the splash image to the root directory and specify -splash:image.gif in the VM arguments. If you want to export a JAR, the FatJar plugin worked for me as I specified.
I hope it helps :)
(sorry for my english, i'm not english :P)
Well guys, I decided yo go my independent way because the Splash class is too monolithic, so here I put my class:
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SplashWindow extends JFrame {
private static final long serialVersionUID = 9090438525613758648L;
private static SplashWindow instance;
private boolean paintCalled = false;
private Image image;
private SplashWindow(Image image) {
super();
this.image = image;
JLabel label = new JLabel();
label.setIcon(new ImageIcon(image));
this.add(label);
this.setUndecorated(true);
this.setAlwaysOnTop(true);
this.pack();
this.setLocationRelativeTo(null);
}
public static void splash(URL imageURL) {
if (imageURL != null) {
splash(Toolkit.getDefaultToolkit().createImage(imageURL));
}
}
public static void splash(Image image) {
if (instance == null && image != null) {
instance = new SplashWindow(image);
instance.setVisible(true);
if (!EventQueue.isDispatchThread() && Runtime.getRuntime().availableProcessors() == 1) {
synchronized (instance) {
while (!instance.paintCalled) {
try {
instance.wait();
} catch (InterruptedException e) {
}
}
}
}
}
}
#Override
public void update(Graphics g) {
paint(g);
}
#Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
if (!paintCalled) {
paintCalled = true;
synchronized (this) {
notifyAll();
}
}
}
public static void disposeSplash() {
instance.setVisible(false);
instance.dispose();
}
}
Hope it helps someone ;)
Related
I am using Intellij Idea - 2021.2.4 and Java 8.
In Intellij, I am not able to read a file in another package in the same module. The file is under main and not resource folder. But in Eclipse, I am able to read.
For example. Below code prints different outputs in both eclipse and intellij.
import java.net.URL;
public class TestMain {
public static void main(String[] args) {
URL resource = TestMain.class.getResource("/org/files/input.txt");
if(resource == null) {
System.out.println("Resource is null");
} else {
System.out.println("Resource found!!");
}
}
}
In Intellij, the code prints "Resource is null", but in eclipse, the code prints "Resource found!!".
Is there any setting I need to enable/disable in intellij ? Why code is behaving different in Intellij Idea ?
HelIo i am trying to make a game engine and right now to create a window with it but there is an error
I included the librarys slack-util and lwjgl before you ask me
The error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: 'void
org.lwjgl.opengl.WindowsDisplay.setWindowProc(java.lang.reflect.Method)'
at org.lwjgl.opengl.WindowsDisplay.setWindowProc(Native Method)
at org.lwjgl.opengl.WindowsDisplay.<clinit>(WindowsDisplay.java:218)
at org.lwjgl.opengl.Display.createDisplayImplementation(Display.java:159)
at org.lwjgl.opengl.Display.<clinit>(Display.java:136)
at com.firenet.engine.Window.createWindow(Window.java:11)
at com.firenet.engine.MainComponent.main(MainComponent.java:11)
Window.java:
package com.firenet.engine;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
public class Window
{
public static void createWindow(int width, int height, String title)
{
Display.setTitle("Test!");
try
{
Display.setDisplayMode(new DisplayMode(width, height));
Display.create();
}
catch (LWJGLException e)
{
e.printStackTrace();
}
}
}
MainComponent.java:
package com.firenet.engine;
public class MainComponent
{
public static final int width = 600;
public static final int height = 500;
public static final String title = "Test!";
public static void main(String[] args)
{
Window.createWindow(width, height, title);
}
}
Your problem seems to be that you have not added the "native" folder to your build path. I have created a project based on the code that you mentioned in the question. After adding the 'natives' correctly I ran your code, and it shows me a blank black window which closes after some time. Try the following:
In your project (I am using Eclipse) go to JRE System Library > Build Path > Configure Build Path (by right clicking on JRE System Library)
Next Select Java Build Path > Libraries (tab) > Native Library Location. Now press 'Edit'
The next step is OS specific. In your download of lwjgl there is a directory 'native'. Select the folder based on the OS you are using. For example if you are using Windows then select lwjgl-2.x.x > native > windows. Now I am on a macOS so I will be using the one for mac.
After this run your application and hopefully you will see a blank window like I see when I run it on my machine.
I'm building a video game and I've built a launcher for my video game as well. The launcher downloads .jar files and stores them in the %appdata% folder for each person who buys the game and downloads the launcher and then runs it.
I need to be able to write a few lines of code to tell the launcher to get the .jar file from the user's computer and run a file from there. The .jar is already compiled and everything is okay and whatnot, but I'm not quite sure how to get the .class file to work with.
Something like this might help:
import System.getPropery("user.home") + "/AppData/Roaming/GameNameHere/bin/game.jar" + ".runGame.class"
And then I could possible do something like this:
if (credentials == true) {
runGame game = new runGame();
game.start();
}
How would I do something like this? Thanks in advance.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
So, I looked the ClassLoader.java class and messed around with it for a bit, but nothing really worked well. What am I doing wrong?
private String location = System.getProperty("user.home") + "\\Desktop\\myJar.jar";
URL url = new URL(location);
public Load() throws Exception {
ClassLoader loader = URLClassLoader.newInstance(new URL[]{url}, getClass().getClassLoader());
Class<?> clazz = Class.forName("gumptastic.MyClass", true, loader);
Method method = clazz.getMethod("output");
method.invoke(this);
}
public static void main(String[] args) {
try {
new Load();
} catch (Exception exc) {
exc.printStackTrace();
}
}
Not sure if you're familiar with this but
I think you should look at class loaders.
http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html
I guess you would need to write a simple one for your particular needs.
Alternatively, it would be even easier if you just use URLClassLoader.
Below is a simple example. This program has no idea of the Gson class
at compile time. But it can successfully load it, create an instance of it,
and use it at runtime. It was tested on Windows 7.
You can download Google Gson from here.
http://code.google.com/p/google-gson/downloads/list
Then place the gson-2.2.4.jar file anywhere you like
on your computer, then point this program to it by
setting arr[0] in the proper way.
Then observe the magic that is taking place :)
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
public class Test007 {
public static void main(String[] args) throws Exception {
URL[] arr = new URL[1];
arr[0] = new URL("file:///dir1/dir2/dir3/gson-2.2.4.jar");
URLClassLoader loader = new URLClassLoader(arr);
Class cls = loader.loadClass("com.google.gson.Gson");
System.out.println(cls);
Constructor constructor = cls.getConstructor(new Class[0]);
Object obj = constructor.newInstance(new Object[0]);
System.out.println(obj);
if (obj!=null){
System.out.println("OK, so now we have an instance of:");
System.out.println(obj.getClass().getName());
}
}
}
i get the error "AWT-EventQueue-0 java.lang.IllegalArgumentException: URI is not hierarchical".
-I'm trying to use the java.awt.Desktop api to open a text file with the OS's default application.
-The application i'm running is launched from the autorunning jar.
I understand that getting a "file from a file" is not the correct way and that it's called resource. I still can't open it and can't figure out how to do this.
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Is there a way to open the resource with the standard os application from my application?
Thx :)
You'd have to extract the file from the Jar to the temp folder and open that temporary file, much like you would do with files in a Zip-file (which a Jar basically is).
You do not have to extract file to /tmp folder. You can read it directly using `getClass().getResourceAsStream()'. But note that path depend on where your txt file is and what's your class' package. If your txt file is packaged in root of jar use '"/prova.txt"'. (pay attention on leading slash).
I don't think you can open it with external applications. As far as i know, all installers extract their compressed content to a temp location and delete them afterwards.
But you can do it inside your Java code with Class.getResource(String name)
http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String)
Wrong
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Right
/**
Do you accept the License Agreement of XYZ app.?
*/
import java.awt.Dimension;
import javax.swing.*;
import java.net.URL;
import java.io.File;
import java.io.IOException;
class ShowThyself {
public static void main(String[] args) throws Exception {
// get an URL to a document..
File file = new File("ShowThyself.java");
final URL url = file.toURI().toURL();
// ..then do this
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JEditorPane license = new JEditorPane();
try {
license.setPage(url);
JScrollPane licenseScroll = new JScrollPane(license);
licenseScroll.setPreferredSize(new Dimension(305,90));
int result = JOptionPane.showConfirmDialog(
null,
licenseScroll,
"EULA",
JOptionPane.OK_CANCEL_OPTION);
if (result==JOptionPane.OK_OPTION) {
System.out.println("Install!");
} else {
System.out.println("Maybe later..");
}
} catch(IOException ioe) {
JOptionPane.showMessageDialog(
null,
"Could not read license!");
}
}
});
}
}
There is JarFile and JarEntry classes from JDK. This allows to load a file from JarFile.
JarFile jarFile = new JarFile("jar_file_Name");
JarEntry entry = jarFile.getJarEntry("resource_file_Name_inside_jar");
InputStream stream = jarFile.getInputStream(entry); // this input stream can be used for specific need
If what you're passing to can accept a java.net.URLthis will work:
this.getClass().getResource("prova.txt")).toURI().toURL()
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);