I'm making a java game using Eclipse. When I export to a runnable jar and try to run the game on different computer the images aren't visible. After checking the web and stack overflow for similar problems I think it has something to do with my using ImageIcon instead of ImageIO. However, I'm not sure how to change my code so that I'm uploading the images with ImageIO instead of ImageIcon.
Here is the method that uses ImageIcon to load the images
void loadImage() {
ImageIcon earth_image_icon = new ImageIcon("earth2.png");
earth = earth_image_icon.getImage();
ImageIcon sun_image_icon = new ImageIcon("sun2.png");
sun = sun_image_icon.getImage();
ImageIcon asteroid_image_icon = new ImageIcon("asteroid.png");
asteroid = asteroid_image_icon.getImage();
ImageIcon bg_image_icon = new ImageIcon("bg_pr.png");
background = bg_image_icon.getImage();
ImageIcon shipA_image_icon = new ImageIcon("ship_alpha.png");
ship_on_asteroid = shipA_image_icon.getImage();
ImageIcon ship_image_icon = new ImageIcon("ship_beta.png");
ship_no_thrust = ship_image_icon.getImage();
ImageIcon shipL_image_icon = new ImageIcon("ship_betaL.png");
ship_left_thrust = shipL_image_icon.getImage();
ImageIcon shipR_image_icon = new ImageIcon("ship_betaR.png");
ship_right_thrust = shipR_image_icon.getImage();
ImageIcon shipU_image_icon = new ImageIcon("ship_betaU.png");
ship_up_thrust = shipU_image_icon.getImage();
ImageIcon shipD_image_icon = new ImageIcon("ship_betaD.png");
ship_down_thrust = shipD_image_icon.getImage();
ImageIcon leftarrow_image_icon = new ImageIcon("leftarrow.png");
leftarrow = leftarrow_image_icon.getImage();
ImageIcon rightarrow_image_icon = new ImageIcon("rightarrow.png");
rightarrow = rightarrow_image_icon.getImage();
ImageIcon downarrow_image_icon = new ImageIcon("downarrow.png");
downarrow = downarrow_image_icon.getImage();
ImageIcon uparrow_image_icon = new ImageIcon("uparrow.png");
uparrow = uparrow_image_icon.getImage();
}
And here is one of the methods that draws the image onto the JPanel as an example
void drawEarth(Graphics g) {
g.drawImage(earth, earth_x_coordinate, earth_y_coordinate, this);
Toolkit.getDefaultToolkit().sync();
}
How do I convert to using ImageIO? I've checked out the Oracle documentation but I'm getting lost trying to sort it out and I'm very new to programming and java at that.
Update It's been suggested that this might be the solution my particular problem but I tried the answers given on this post and they didn't work for my case.
You will need to include the image resources in your compiled jar. An easy way of doing this if you are using an IDE like eclipse is to create a res or img folder and put your files in there. (Use the methods given here.)
In that case, you probably won't need to use ImageIO. However, if you still want to use ImageIO (which is recommended because of its wider support for formats and better exception handling, as mentioned in the comments), you can do the following:
Icon foo = new ImageIcon(ImageIO.read(getClass().getResource("foo.png")))
I created a new project in eclipse and copied the class files into the new projects src folder. I then made a resource folder, added it to the build path, created an images package in that resource folder and copied the images into that images package. For some reason this all worked. Thanks everyone for your help
Related
I am trying to retrieve a picture by relative path but it always returns a java.lang.NullPointerException no matter what path combination I try
private final Icon cardBack = new ImageIcon(getClass().getResource(
"src/main/resources/Images/cardIcons/cardBack.png"));
https://pastebin.com/sDjP87p3
I've ran into this error before. You have to add the " / " before your path.
I believe the NPE is being thrown from the ImageIcon constructor as getResource is returning null.
Try the following:
private final Icon cardBack = new ImageIcon(getClass().getClassLoader().getResource("src/main/resources/Images/cardIcons/cardBack.png"));
Or:
private final Icon cardBack = new ImageIcon(ClassLoader.getSystemResource("src/main/resources/Images/cardIcons/cardBack.png"));
private final Icon cardBack = new ImageIcon(getClass().getResource("/Images/cardIcons/cardBack.png"));
Worked after I remade the app into a normal java project. Apparently the problem was caused by Maven, cause yet unknown.
i have an application that loads an image to create a button with an icon in it. When started from the IDE, it works just fine, but when started from an exported jar file, it gives an image fetching error.
Location of images :
+Project
-Source Packages
-Tools
-start.jpg
The code used :
static final String STARTIMAGE = "/Tools/start.JPG";
public static JButton createStartButton() {
Image img = Toolkit.getDefaultToolkit().getImage(GUITools.class.getResource(STARTIMAGE));
JButton b = new JButton("",new ImageIcon(img));
b.setPreferredSize(smallButton);
b.setMaximumSize(smallButton);
b.setMinimumSize(smallButton);
return b;
Now, the weirdest thing is that in another screen, a button is created in the exact same way, and this one works just fine...
Code:
static final String PREVIOUSIMAGE = "/Tools/previous.gif";
public JButton createPreviousButton(){
Image img = Toolkit.getDefaultToolkit().getImage(getClass().getResource(PREVIOUSIMAGE));
JButton b = new JButton("Previous",new ImageIcon(img));
b.setPreferredSize(dimensionButton);
b.setMaximumSize(dimensionButton);
b.setMinimumSize(dimensionButton);
return b;
}
The only difference is that one is static, but even if make it non-static like the other one, it still won't work.
I tried everything I found on this forum and other sites, including this good topic :
How to bundle images in jar file
(The generated url at the end of the topic is just 'null')
Nothing seems to work... Please help!
Thanks!
When started from the IDE, it works just fine, but when started from an exported jar file, it gives an image fetching error.
Image img = Toolkit.getDefaultToolkit().getImage(getClass().getResource(PREVIOUSIMAGE));
This approach above is incorrect, use this instead:
private static BufferedImage readBufferedImage (String imagePath) {
try {
InputStream is = YourClassName.class.getClassLoader().getResourceAsStream(imagePath);
BufferedImage bimage = ImageIO.read(is);
is.close();
return bimage;
} catch (Exception e) {
return null;
}
}
And better load all images at application startup and then use them.
It seems to me that your images are inside a package so the actual link might be "package.name/Tools/start.jpg" or something else when its compiled so the image should be moved.
Instead of having it inside of a package like:
+Project
-Source Packages
-Tools
-start.jpg
Do something like this instead.
+Project Folder
-Source Packages/
-Tools/
-start.jpg
I am using a Java applet to take a screenshot of the web browser, using Java's Robot class.
Robot objRobot = new Robot ();
BufferedImage objBufferedImage = objRobot.createScreenCapture(objRectArea);
The thing works good in Windows system, taking screenshot. But in case of Mac OS X I get a blank image.
When I check the event viewer, I see the following error:
invalid context
invalid pixel format
CoreAnimation: rendering error 506
The problem is occurring for all the browsers Safari, Firefox and Chrome. My applet is a signed applet.
What might be the reason?
My machine configuration is as follows:
OS : MAC OS X
Version : 10.6.4
I've sent the error message invalid pixel format to google and received a long list of results (close to 10.000) - it looks as if the problem is not a Java problem but a configuration issue on your Mac.
Try to change display resolutions and re-run your applet. Good chance, that the error is linked to some screen resolutions (external display?). Some suggestions on the web were to fully update you OSX.
dir Robot objRobot = null;
try
{
objRobot = new Robot();
} catch(Exception ex)
{
}
Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
BufferedImage objBufferedImage = objRobot.createScreenCapture(new Rectangle(0, 0, (int)screenDim.getWidth(), (int)screenDim.getHeight()));
int areaToExportWidth = 1024;
int areaToExportHeight = 768;
//Create the image
BufferedImage exportImage =objRobot.createScreenCapture(new Rectangle(0, 0, (int)screenDim.getWidth(), (int)screenDim.getHeight()));
//Get graphics - Get the layer we can actually draw on
Graphics2D imageGraphics = (Graphics2D) exportImage.getGraphics();
//Cleanup after ourselves
imageGraphics.dispose();
//Setup to write the BufferedImage to a file
String pathToFile = "dir";
File outputDirectory = new File(pathToFile);
File outputFile = new File(pathToFile+"\\"+counter+"MyImage.png");
//Here we make sure the directory exists.
/*
* Returns TRUE if:
* The directory is MISSING
* and/or the directory IS NOT a directory
*/
if(!outputDirectory.exists() || !outputDirectory.isDirectory()){
outputDirectory.mkdirs(); //Make the directory
} // Else do nothing
//Write the file
try { //Attempt the write
ImageIO.write(exportImage, "png", outputFile);
} catch (IOException e) { //For some reason it failed so...
e.printStackTrace(); //... why did it fail?
}
I have to be able to load and draw X amount of images located on a network based drive.
I need help finding a way to load the images asynchronously.
java.net.URL Loc = new URL("http://auroragm.sourceforge.net/GameCover/GameCases/Mass-Effect.png");
JLabel lbl = new JLabel();
lbl.setIcon((anotherIcon = new ImageIcon(Loc)));
The above is one image which loads on the GUI thread and thus would freeze if 20 more were to be loaded. Any help would be appreciated
Load the images in separate thread. Please treat below code as pseudo-code:
final java.net.URL Loc = new URL("http://.../Mass-Effect.png");
Thread t = new Thread(new Runnable() {
public void run() {
Object content = Loc.getContent();
// content would be probably some Image class or byte[]
// or:
// InputStream in = Loc.openStream();
// read image from in
}
);
Short answer: you should load the images on another thread.
Swing does provide a nice set of classes & patterns for this:
http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html
I created a method which changes the icon of all jradiobuttons from a buttongroup:
public void setRadioButtonIcons(final ButtonGroup gruppe){
Enumeration<AbstractButton> gruppeEnum = gruppe.getElements();
while (gruppeEnum.hasMoreElements()){
AbstractButton radio = gruppeEnum.nextElement();
Icon unselIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox0.jpg").getPath());
Icon selIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox1.jpg").getPath());
radio.setIcon(unselIcon);
radio.setSelectedIcon(selIcon);
}
}
This works fine under Ubuntu with Java 1.6.0_16.
When I use the methode under windows 7 with java 1.6.0_18, the icons do not apear. They are simply missing. The programm does not throw a Nullpointer... it finds the icons, but does not display them. Any ideas? It seems somewhat hard to believe that I can not use such a simple functionality under windows.
I tried it with gif and jpg. I also put the images inside the jar and tried to load them from the filesystem -> same result.
Edit: In this configuration, the files are loaded from the jar.
Icon unselIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox0.jpg").getPath());
Icon selIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox1.jpg").getPath());
You shouldn't be calling getPath() there, should just be:
Icon unselIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox0.jpg"));
Icon selIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox1.jpg"));
It won't be able to access a resource in a jar by path and an ImageIcon can load an image using a URL just fine.
If you still are not seeing your icons then it may be that the L&F you are using does not use those icons and instead uses its own. Perhaps try testing the code with a different L&F.
Try removing the calls to getPath(), like this:
public void setRadioButtonIcons(final ButtonGroup gruppe) {
Enumeration<AbstractButton> gruppeEnum = gruppe.getElements();
while (gruppeEnum.hasMoreElements()){
AbstractButton radio = gruppeEnum.nextElement();
Icon unselIcon = new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("checkbox0.jpg"));
Icon selIcon = new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("checkbox1.jpg"));
radio.setIcon(unselIcon);
radio.setSelectedIcon(selIcon);
}
}
The problem is that URL.getPath() gives you a string URL, which isn't necessarily a valid string filename of the sort that the ImageIcon string constructor expects. Fortunately, ImageIcon has another constructor that understands URL objects, and so there's no need to call getPath().