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);
Related
I try to display an image using a JLabel. This is my project navigator:
From SettingsDialog.java I want to display an image using following code:
String path = "/images/sidebar-icon-48.png";
File file = new File(path);
Image image;
try {
image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
header.add(label); // header is a JPanel
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The code throws an exception: Can't read input file!
Is the path of the image is wrong?
Don't read from a file, read from the class path
image = ImageIO.read(getClass().getResource(path));
-or-
image = ImageIO.read(MyClass.class.getResource(path));
When you use a File object, you're telling the program to read from the file system, which will make your path invalid. The path you are using is correct though, when reading from the class path, as you should be doing.
See the wiki on embedded resource. Also see getResource()
UPDATE Test Run
package org.apache.openoffice.sidebar;
import javax.swing.*;
public class SomeClass {
public SomeClass() {
ImageIcon icon = new ImageIcon(
SomeClass.class.getResource("/images/sidebar-icon-48.png"));
JLabel label = new JLabel(icon);
JFrame frame = new JFrame("Test");
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new SomeClass();
}
});
}
}
"/images/sidebar-icon-48.png" is root path. On windows would be c:\images\sidebar-icon-48.png or d:\images\sidebar-icon-48.png depending on current drive (java converts the / to \ - not an issue). Linux images would a child of root /images/sidebar-icon-48.png Need to load relative to class or relative to the jar that had the class (if you do not want to store images inside jar.
In big projects its nice to have images and other resources outside the jar so the jar is smaller and more importantly its easy to change the resources without fiddling with jars/ wars.
Since you seem to be making a add on for open office, you will have to keep everything in jar and so peeskillet answer is right. But make sure your images folder is being packed in the jar. Extract the jar ising the jar command or rename the file to zip and extract.
Or check and fix project settings. How to make a jar in eclipse ... latest one has a wizard that makes an ant script or this SO
try to use this directly :
JLabel label = new JLabel(new ImageIcon(path));
and delete these line :
File file = new File(path);
image = ImageIO.read(file);
if error still exist paste the following error
I am new to Sikuli and I wanted to
1. click windows button, and
2. type "Helloworld"
3. press Enter.
I have coded this and working Successfully in Sikuli IDE
click("1391583846712.png")
type("helloWorld")
wait(2)
type(Key.ENTER)
I tried to move this to Java ,
From the sikuli javadocs I have seen the following code, However it is not working in java sikuli-api-1.0.2 and latest version
import org.sikuli.script.*;
public class TestSikuli {
public static void main(String[] args) {
Screen s = new Screen();
try{
s.click("imgs/win-start.png", 0);
s.wait("imgs/spotlight-input.png");
s.type(null, "hello world\n", 0);
}
catch(FindFailed e){
e.printStackTrace();
}
}
}
It tells that Screen is an interface . Please tell me how to make it working in latest java sikuli-api. Please see that I am very new to Sikuli . Any suggestions will be highly appreciated. Also Please point me to the right sikuli java for begineers
new org.sikuli.api.DesktopScreenRegion() creates a ScreenRegion on the base full screen where you can click and seek your images
Your best bet to find how the new API is built is to look at the sources. There aren't a lot of classes to understand, fortunately.
The following Sikuli Java code should work:
import org.sikuli.script.*;
public class HelloWorld {
public static void main(String[] args){
Screen screen = new Screen();
try{
screen.click("D:\\Sikuli\\WinStartButton.png");
//"WinStartButton.png" must exist on the desired location you are using
//OR, instead of above line you can use the following:
screen.type(Key.WIN);
}
catch(FindFailed e){
e.getStackTrace();
}
screen.type("Hello World");
screen.type(Key.ENTER);
}
}
Try to use image locator in your code,
import org.sikuli.script.*;
import org.sikuli.basics.ImageLocator;
public class AuthLogin {
public static void main(String[] args) {
Screen s = new Screen();
ImageLocator.setBundlePath("path to img directory");
try{
s.click("win-start.png", 0);
s.wait("spotlight-input.png");
s.type(null, "hello world\n", 0);
}
catch(FindFailed e){
e.printStackTrace();
}
}
I think you should not use the absolute image path directly in the code.
I would create a class which contains the absolute paths as static constants.
Example :
instead of :
screen.click( "D:\\Sikuli\\WinStartButton.png");
you can do it like this :
public static final String IMAGE = "D:\\Sikuli\\WinStartButton.png";
screen.click(IMAGE);
Use Keydown and Keyup method for Enter key pressed
I have tried to organize the entire code. please let me know if its working.
Screen sikuli = new Screen();
String message = "hello world";
Pattern imgLocator = "";
if(sikuli.exists(imgLocator)!=null) {
sikuli.find(imgLocator);
sikuli.click(imgLocator);
sikuli.wait(2);
sikuli.type(imgLocator, message);
}
sikuli.keyDown(Key.ENTER);
sikuli.keyUp(Key.ENTER);
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'm using eclipse to created an RCP Application, and I'm not being able to load an image because I don't know how to find it in the generated code. I'm going to try to explain my particular issue.
Note: the project is a Game editor, and it is located here: http://chelder86.github.com/ArcadeTongame/
Firstly, this is the project structure:
The next code runs the RCP application correctly inside Eclipse, after changing the Working Workspace in the Eclipse Running Config.
package figures;
(...)
public class Sound extends ImageFigure {
public Sound() {
String picturePath = "src/figures/Sound48.png";
// or String picturePath = "bin/figures/Sound48.png";
Image image = new Image(null, picturePath);
this.setImage(image);
}
}
But it does not work when I create a Product and export it as an RCP Application. I mean, the RCP application works, but it does not load that image.
Note: build.properties has the image checked.
I tried different combinations like these with the same result: java.io.FileNotFoundException, when I run it in Eclipse:
package figures;
(...)
public class Sound extends ImageFigure {
public Sound() {
String picturePath = getClass().getResource("Sound48.png").getPath();
// or String picturePath = this.getClass().getClassLoader().getResource("bin/figures/Sound48.png").getPath();
// or String picturePath = this.getClass().getClassLoader().getResource("figures/Sound48.png").getHost();
// or similars
Image image = new Image(null, picturePath);
this.setImage(image);
}
}
How could I load it correctly?
Thanks for any help! :)
Carlos
Try creating a separate "figures" folder alongside "icons" folder. Put only the image files there, not .java files. Don't forget to add it to the class path and to build.properties. Then something like this should work:
InputStream in = getClass().getResourceAsStream("figures/Sound48.png");
Image image = new Image(Display.getDefault(), in);
I have a JEditorPane created by this way:
JEditorPane pane = new JEditorPane("text/html", "<font face='Arial'>" + my_text_to_show + "<img src='/root/img.gif'/>" + "</font>");
I put this pane on a JFrame.
Text is shown correctly, but I can't see the picture, there is only a square indicating that there should be an image (i.e.: "broken image" shown by browsers when picture has not been found)
You have to provide type, and get the resource. That's all. My tested example, but I'm not sure about formating. Hope it helps:
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
public class Test extends JFrame {
public static void main(String[] args) throws Exception {
Test.createAndShowGUI();
}
private static void createAndShowGUI() throws IOException {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String imgsrc =
Test.class.getClassLoader().getSystemResource("a.jpg").toString();
frame.getContentPane().add(new JEditorPane("text/html",
"<html><img src='"+imgsrc+"' width=200height=200></img>"));
frame.pack();
frame.setVisible(true);
}
}
The JEditorPane is using HTMLDocument.getBase to locate relative urls as well, so if you are displaying content from a directory, make sure to set the base on the html document so it resolves urls relative to the base directory.
Depending on where that image actually is, you might want to extend HTMLEditorKit+HTMLFactory+ImageView and provide a custom implementation of ImageView, which is responsible for mapping the attribute URL to the image URL, too.
None of the above worked for me, however 'imgsrc = new File("passport.jpg").toURL().toExternalForm();' let me to try and have each image in the html have a preceding 'file:' so that it now reads:
<img src="file:passport.jpg" />
And that works fine for me.
If you want to specify relative path to the image.
Let's say your project folder structure is as following:
sample_project/images
sample_project/images/loading.gif
sample_project/src
sampler_project/src/package_name
Now the image tag would look like this:
"<img src='file:images/loading.gif' width='100' height='100'>"
Yaay!
I used this when I was working in netbeans, it worked though. I think a little modification if the program should run outside of netbeans,
String imgsrc="";
try {
imgsrc = new File("passport.jpg").toURL().toExternalForm();
} catch (MalformedURLException ex) {
Logger.getLogger(EntityManager.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println(imgsrc); use this to check
html = "<img src='" + imgsrc + "' alt='' name='passport' width='74' height='85' /><br />";
//use the html ...
if you run from the jar, the image file has to be on the same directory level, ...
in fact, the image file has to be on the same directory as your execution entry.