I recently finished the basics of a game that I'm making and I was going to send it to some friends, but whenever they open the .jar it's just a grey window. When I heard that I assumed it was because of the way I got the images (I used a full path: C:\Users\etc). I did some Googling and found a way to get images that seemed more efficient.
private static Image[] mobImages = new Image[1];
public static void loadImages()
{
mobImages[1] = Handler.loadImage("res/EnemyLv1.png");
}
public static Image getMobImages(int index)
{
return mobImages[index];
}
That's what I would like to use. But I did that and changed the rest of my code to support that. And whenever I run a game I get a few errors. Which all point back to
this:
if(getBounds().intersects(tempEnemy.getBounds()))
and so probably the way I'm getting the images too. How could I fix this? And are there better ways to get Images? I've tried a few but they haven't worked.
EDIT: I finally solved all of the errors! :D The only problem is that none of the images appear. Here's my code again. Any more help? That would be fantastic! Thanks everybody for the support so far!
Hard to say whats going wrong in your code. However I recommend you put your image files into a package in the java project (so they will be part of the JAR file) and access them using Class.getResource()/Class.getResourceAsStream(). That avoids multiple pitfalls and keeps everything together.
A sample how to structure your images into the packages:
myproject
images
ImageLocator.class
MyImage1.jpg
MyImage2.jpg
The ImageLocator class then needs to use relative pathes (just the image name + extension) to access to resources.
public class ImageLocator {
public final static String IMAGE_NAME1 = "MyImage1.jpg";
public static Image getImage(final String name) {
URL url = ImageLocator.class.getResource(name);
Image image = Toolkit.getDefaultToolkit().createImage(url);
// ensure the image is loaded
return new ImageIcon(image).getImage();
}
}
This can be done more elegant, but this should get you started. Defining the image names as constants in the ImageLocator class avoids spreading the concrete path throughout the project (as long as the name is correct in ImageLocator, everything else will be checked by the compiler)
Your code still uses "C:\Users\Kids\Desktop\Java Game\Cosmic Defense\res\EnemyLv2.png" in Enemy.java. Are you sure this exists? If you moved the Cosmic Defense folder, it will not.
(You were talking about changing absolute paths to relative paths, so this may be your problem)
Part of the reason could be that your code is pointing to an index of "1" in an array of size 1, meaning that the only available index is in fact "0".
Try mobImages[0] = Handler.loadImage("res/EnemyLv1.png");
Related
I think I'm doing everything right in my code but my background won't show up in my processing project, here is my code.
package finalproject;
import processing.core.PApplet;
import processing.core.PImage;
public class FinalProject extends PApplet {
PImage background;
PImage player;
public void setup() {
size(1360, 1080);
player = loadImage("player.png");
background = loadImage("rust.png");
}
public void draw() {
background(background);
image(player, 500, 500);
}
}
Processing expects files to be inside a data directory next to the code.
You're presumably running this from an IDE like Eclipse instead of the Processing editor, so where you put that data directory depends on how your code is setup. And you haven't posted a MCVE, so it's hard to help you with that.
But basically, you need to debug your sketch to figure out exactly where Processing is looking for the files. Then you need to move the files there. This is probably something simple like putting them inside a data directory.
If you still can't get it working, please post a MCVE along with a screenshot or a description of your directory structure.
If you are using the processing IDE than the data folder should be located in your sketch folder next to all the .pde files. Make sure that the image you are using has the same resolution as the sketch window. If you are still having issues I would recommend that you try moving your setup and draw methods out of your class and into the main processing sketch.
I have problem with Image Icons. I know that this have been asked before, but I can't figure out how to fix this, becouse I think my problem is different. When I launch app with eclipse, all works. But when I make it runnable jar, it won't show images.
Some code of my ImagesHolder Class :
package Clicker;
import javax.swing.ImageIcon;
public class ImagesHolder {
final public ImageIcon AccessoriesIcon = new ImageIcon("Images/Part_Accessories.png");
final public ImageIcon BodyIcon = new ImageIcon("Images/Part_Body.png");
final public ImageIcon BrakesIcon = new ImageIcon("Images/Part_Brakes.png");
final public ImageIcon CoolingIcon = new ImageIcon("Images/Part_Cooling.png");
final public ImageIcon ElectronicsIcon = new ImageIcon("Images/Part_Electronics.png");
final public ImageIcon EngineIcon = new ImageIcon("Images/Part_Engine.png");
final public ImageIcon ExaustIcon = new ImageIcon("Images/Part_Exaust.png");
final public ImageIcon FuelIcon = new ImageIcon("Images/Part_Fuel.png");
final public ImageIcon InteriorIcon = new ImageIcon("Images/Part_Interior.png");
final public ImageIcon SteeringIcon = new ImageIcon("Images/Part_Steering.png");
final public ImageIcon SuspensionIcon = new ImageIcon("Images/Part_Suspension.png");
final public ImageIcon TransmissionIcon = new ImageIcon("Images/Part_Transmission.png");
final public ImageIcon TiresIcon = new ImageIcon("Images/Part_Tires.png");
And If I make Images as URL, i can't reset image icons, like here (I have Labels and I want to change label icon)
Labels example :
public JLabel AccessoriesLVL1Label = new JLabel(ImagesHolder.LockedIcon);
AccessoriesLVL1Label.setHorizontalTextPosition(JLabel.CENTER);
AccessoriesLVL1Label.setVerticalTextPosition(JLabel.BOTTOM);
AccessoriesLVL1Label.setText("<html>Accessories LVL 1<br>" + "Count: " + Part.parts[1]);
And change :
if(CarMain.main[5] >=1){
jbtnSellAccessoriesLv1.setEnabled(true);
Labels.AccessoriesLVL1Label.setIcon(ImagesHolder.AccessoriesIcon);
}
Edited:
If I this :
final public ImageIcon MoneyIcon = new ImageIcon("Images/Money.png");
Make as :
URL MoneyIcon = ImagesHolder.class.getResource("/Money.png");
I get error in this line:
Labels.MoneyLabel.setIcon(ImagesHolder.MoneyIcon);
Error :
The method setIcon(Icon) in the type JLabel is not applicable for the arguments (URL)
There is an alternative for getting images from jar file:
Ideal way would be to have a resource directory under your project root and include it into the list of source code directories. This will result in all images there being copied into the JAR. If you make a sub directory there, resources/image, then you'll end up with a JAR that has an image directory. You access those images through the classloader:
classloader.getResourceAsStream("/image/image1.jpg");
or,
classloader.getResource("/image/image2.jpg");
Refer this link for in detail example.
Well, to sum up the previously given answers:
I guess a potential solution would be to use classloader as Dark Knight proposed. Furthermore you just need to create a new ImageIcon before setting it.
URL MoneyIcon = ImagesHolder.class.getResource("/Money.png");
Labels.MoneyLabel.setIcon(new ImagesIcon(ImagesHolder.MoneyIcon));
Because if you look through your code again, I guess it somewhat makes sense it does not work. I mean you want to set an ImageIcon, yet the last thing you have is an URL object. That this must throw an error should make sense. Yet as Andrew Thompson already said: You can construct an ImageIcon from that URL as displayed/explained above.
And since you also explained that you had issues with the directories (getting the structure from source to compiled) I want to add some links for further reading: If you just use 'plain' Java (no build tools) maybe this link can help: Copying data files upon build in Java/Eclipse. It is mainly written for Eclipse, but I guess most other IDEs should provide similar options.
From my current projects I could also recommend to use a tool like Maven. For smaller projects it might be a little over the top, but it takes of a lot of work (e.g. library handling, handling of resources like images etc.). These are just some parts that might be useful for you. If this is of interest for you I guess you will find lots of useful resources on the web since Maven (or other tools like Ant and Gradle) are quite commonly used.
I have encountered a small problem that I need some help on. The issue is that I wish to call a browser window which calls a html page. The html file opens in 3 different browsers so the code for that should be correct. The actual problem is that it brings up a page can't be displayed error message
Here is the code that gets the location
package org.error;
public class BrowserLocation {
private String test1 = "org\\error\\PatientNumberError.html";
public BrowserLocation() {
}
public String patientNumberAddress() {
return test1;
}
}
and here is the code that creates the browser component and calls the location of the html file.
Browser browser = new Browser(container, SWT.NONE);
browser.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE));
browser.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
browser.setUrl(browserLocation.patientNumberAddress());
browser.setBounds(25, 25, 315, 180);
Would it be possible to find the error of my ways?
setUrl require a URL so you need something like:
browser.setUrl(new File(path).toURI().toURL().toString());
Sorry for not getting back to you earlier.
Someone that I know who is a senior Java programmer told me the problem that I was having was a case of absolute address versus relative address.
The reason for this is that if I was reading and writing to a file, then I would be able to use a relative address. However If I'm interacting with a server which is the case here as eventually It could go on-line (If I had the money) it would need to be an absolute address.
As I am still learning Java programming this was a very specific and important lesson to learn. I hope this would help anybody else who has had this issue.
I am trying to add a Map to my libgdx app as a proof of concept. It seems that no matter how I make a packfile, the com.badlogic.gdx.graphics.g2d.tiled.TileAtlas constructor TileAtlas(TiledMap map, FileHandle inputDir) will not correctly read it. My Tile Map is simple and has only 2 tiles, and both the external gui and internal system will generate a packed file.
Here's the issue, either I name the packfile with a filename to match one of my images to satisfy line 2 below, or the method errors out. If I add 2 packfiles, one for each name of an image in my tile set, I find the Atlas isn't constructed correctly in memory. What am I missing here? Should there only ever be one tile in a tilemap?
Code from Libgdx:
for (TileSet set : map.tileSets) {
FileHandle packfile = getRelativeFileHandle(inputDir, removeExtension(set.imageName) + " packfile");
TextureAtlas textureAtlas = new TextureAtlas(packfile, packfile.parent(), false);
Array<AtlasRegion> atlasRegions = textureAtlas.findRegions(removeExtension(removePath(set.imageName)));
for (AtlasRegion reg : atlasRegions) {
regionsMap.put(reg.index + set.firstgid, reg);
if (!textures.contains(reg.getTexture())) {
textures.add(reg.getTexture());
}
}
}
com.badlogic.gdx.graphics.g2d.tiled --> It looks like you're using the old tiled API. I don't even think that package exists anymore, so you should probably download a newer version.
Check out this blog article. I haven't used the new API yet, but at a quick glance it looks much easier to load maps.
I have a small JApplet that is supposed to simply import an image and display it on screen. However, I am having some trouble with it.
private Image logo1;
public void init() {
logo1 = getImage( getCodeBase(), "Penguins.jpg" );
}
#Override
public void paint( Graphics g ) {
g.drawImage( logo1, 0, 0, this );
}
That is essentially my entire program. Is there any problem with it? I am assuming one of the problems might be that the picture might have to be in a specific part of your computer or something like that...The address for this image is C:\Users\Public\Pictures\Sample Pictures
The reason that getCodeBase() is in the method call of getImage() is to get the codebase location.
The codebase is the folder that holds all of your source packages. It's most likely the folder above your src folder for your project. Here's the basic structure of a normal project (at least my projects):
-MyProject - This is the codebase
-src - All of your code is probably in this folder. All packages show up as folders here
-bin - When your code compiles, it ends up here
-data - This is where all of the resources are held (my preference)
-images - Pretty obvious, the image would go here
-Penguin.jpg - Your image
All this leads up to this answer: With the above structure, your call to getImage() should read:
getImage(getCodeBase(), 'data/images/Penguin.jpg');
Try including the image that you want to display in the folder of your java program. Sometimes if the image is in another folder, it's not displayed in the applet.
I too faced a similar problem. Just copy the image into your project folder.
public void init() {
Picture = getImage(getDocumentBase(),"image.gif");
}
I use this code. Do following steps to add your image:
Clean and Build the project
Add the image into build folder of your project.
Run the project.