so i have made a 2D game using slick however the only resource loader that i have ever made is for plain java and it went like this :
import java.awt.Image;
import java.awt.Toolkit;
public class ResourceLoader {
static ResourceLoader rl = new ResourceLoader();
public static Image getImage(String fileName){
return Toolkit.getDefaultToolkit().getImage(rl.getClass().getResource("images/" + fileName));
}
}
Slick, of course, has a different image type (org.newdawn.slick.Image) for which this Resource Loader Class will not work and so i do not know how, for when i export my project , to load resources. I have searched online but haven't found many detailed results and so i ask is there any way to load resources so when i export the project as a run able jar file it will still load them.
thanks for any helpful answers in advance - josh
Not sure if you've seen it but here's one way of doing this. Explains deferred loading:
http://slick.cokeandcode.com/wiki/doku.php?id=resource_manager_tutorial
You might want to check out the other tutorials by Spiegel if you're starting out with Slick2D. I've found them very useful
Related
I have been trying to do a kind of plugin-system using the ServiceLoader. There are 2 modules, the first provides the abstract class LoadedRealmPlugin. The second one extends this class. I have added the file corresponding to the full name of the ServiceProvider and added the service-class to it. IntelliJ does not find any errors (but when changing the filename or classname it does). Here is the structure:
MainModule
src
main
java
com.interestingcompany.mainmodule
LoadedRealmPlugin
MainModule.iml
Plugin
META-INF
services
com.interestingcompany.mainmodule (-> Content: "PluginExtension")
src
PluginExtension
Plugin.iml
(This is simplified, I left out classes that (I think) are not important to the ServiceLoader. I can post a screenshot of the actual structure if anyone needs it)
Here is the code I use to load the Service:
File file = new File("Plugins/Plugin.jar");
URLClassLoader c = new URLClassLoader(new URL[]{file.getAbsoluteFile().toURI().toURL()});
ServiceLoader<LoadedRealmPlugin> loader = ServiceLoader.load(LoadedRealmPlugin.class, c);
LoadedRealmPlugin p = loader.iterator().next(); // Throws a java.util.NoSuchElementException
p.Initialize(RealmPath); // Abstract method implemented in the service
return p;
When trying to run it, I always get an empty ServiceLoader. I looked at this post, but I was not quite sure about how to apply that answer since I am trying to load my plugin from a file. In addition, I found this post. Yet, there was no answer, just some comments that did not seem to have answered the question.
As you might have been able to tell, this is my first time working with classloaders. If there is any additional information needed, just ask me. Thank you for reading through my beginner troubles.
package-less classes are in the unnamed package, which is inaccessible to rather a lot of code, notably including here.
Put PluginExtension.java in a package, make sure the content of your META-INF/services/com.ic.mainmodule file reflects this (content should be pkg.PluginExtension), and it'll work fine.
I can't help it but think I've missed just the Thread to answer my question but I've been looking for a long time now and can't seem to find the help I need.
My problem is quite simple:
I've created a game (or rather I'm in the process of it) and I'm trying to add sprites (png files for the enemies and such) to it. Loading them in the IDE works just fine but when I create a jar file and try to open it, it simply says "A Java Exception has occurred". Further investigation revealed the problem is that it can't find the files I told it to load.
Through the threads I've read I gathered this much:
It's either that I'm not loading the images properly, meaning that I don't use the proper code for it, or
my MANIFEST.mf does not contain a "Class-Path" (meaning that the arguments are blank, which in fact they are)
Finding other code didn't work out for me. People suggested to use a ClassLoader which I could't manage to get working. Trying it out gave me nullpointer exceptions.
Trying to look into the latter didn't do much help, because I couldn't find any helping information, or I'm just not understanding anything.
package platformer.resources;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.*;
public class ImageLoader
{
static String spritePath = "src/platformer/resources/";
public static BufferedImage loadImage(String path)
{
BufferedImage img = null;
try{img= ImageIO.read(new File(spritePath+path));
}catch(IOException e){System.out.println("Couldn't load File: "+spritePath+path);}
return img;
}
public static BufferedImage flipImage(BufferedImage bufferedImage)
{
AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
tx.translate(-bufferedImage.getWidth(null), 0);
AffineTransformOp op = new AffineTransformOp(tx,
AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
bufferedImage = op.filter(bufferedImage, null);
return bufferedImage;
}
}
This is the code I used so far.
Other classes would use "loadImage" or "flipImage" and in the IDE it works fine but as a .jar it fails to find the .png.
For example the class "platformer/entities/walker.class" would try to open the "Idle.png". In order to do that it uses the "loadImage("/entities/enemy/walker/Idle.png")" method. Note that in the method the actual path would end up being "src/platformer/resources/entities/enemy/walker/Idle.png".
Again, I'm terribly sorry if this has already been answered but I appreciate your help nonetheless.
Michael
When your files are inside a jar they can only be taken out as a resource stream so you will want to use something like:
ImageLoader.class.getResourceAsStream("nameoffile").
This is because a jar is actually a zipped up directory structure and files are not really files they are hidden amongst a compressed zip formatting as binary.
Hello I have a problem with importing an image from my resources folder. I have looked all over google (or so I think) and I have no idea what I am doing wrong.
All help is appreciated thanks
Here is the picture of my java project:
Here is my Game Code:
public Game(){
handler = new Handler();
this.addKeyListener(new KeyInput(handler));
new Window(WIDTH, HEIGHT, "Testing", this);
BufferedImageLoader loader = new BufferedImageLoader();
level = loader.loadImage("/level.png");
hud = new HUD();
spawn = new Spawn(handler, hud);
r = new Random();
walls = new WallsMap(handler);
cam = new Camera(0, 0);
walls.render();
handler.addObject(new Player(WIDTH/2-32, HEIGHT/2-32, ID.Player, handler));
}
Finally here is my BufferedImageLoader class:
public class BufferedImageLoader {
private BufferedImage image;
public BufferedImage loadImage(String path){
try {
image = ImageIO.read(getClass().getClassLoader().getResourceAsStream(path));
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
}
To solve your particular problem, either of these two options should work so that the resource can be properly located:
Remove the call to getClassLoader() from your loadImage method so that the call is just getClass().getResourceAsStream(path) -OR-
Remove the slash from "/level.png" so that your call to loadImage looks like loader.loadImage("level.png")
However, in general, I agree with mastercork889, that it is better practice to organize your resources into packages as well.
EDIT:
In response to mastercork889's comment saying that my answer should be AND instead of OR, I thought I should elaborate on why it is indeed exclusive OR. I would have just commented, but I'm still too new to stack overflow to be allowed to comment, and this is quite a bit of information anyway :)
Removing the call to getClassLoader() works because then you're using the getResourceAsStream() method from the Class class, which does extra work before delegation to the getResourceAsStream() method from the ClassLoader class.
From the Java API:
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Since your resource isn't in a package, and is at the top level of a source folder (it looks like res is an "Eclipse Source Folder"), the level.png portion following the slash will adequately identify the location of the resource in an absolute way.
OR
Removing the slash from "/level.png" also works because then when the object's class loader (which should be the system class loader) looks for the resource, it will attempt to resolve your resource in an absolute way. The special handling of the slash at the beginning is behavior that is specific to the getResourceAsStream() method in Class, not ClassLoader.
The reason that AND won't work, is because if you call the getResourceAsStream() method from Class and remove the slash, then it will attempt to locate the resource in the same package that the associated class is located in. If you choose to go with the AND option, then you would need to move level.png into the com.plat.gfx package.
As a final point, I have built a small test program that followed the same format as your example, and once I followed one of the two suggestions, it worked for me.
The subtleties of resources, classes, and class loaders can be quite tricky. Good luck with your project!
Don't worry about putting images in a specific folder. Instead put them also in the src folder under a specific package: com.plat.res
I find that putting images in a specific package makes the package hierarchy look much more efficient, and less spaghetti-like.
Also a note on package conventions: domain-extension.domain.main-program.etc. My package hierarchy looks like this:
com.brennytizer.jumg
com.brennytizer.jumg.res
com.brennytizer.jumg.engine
com.brennytizer.jumg.level
com.brennytizer.jumg.level.maps
If you don't have a domain, write in what you think your domain would be (if you were to buy it in the future), or just use your (backwards) name:
My name is Jarod Brennfleck, writing program foobar, my package would be: brennfleck.jarod.foobar.
Once in there use the ImageIO class: ImageIO.read(Game.class.getResourceAsStream("/com/plat/res/leve.png"));
I am programming an extension for analyzing files in an deliver changesets to a stream.
It is an Advisor because if the analyze fails then you can't deliver anything.
In addition I have read the articles:
https://jazz.net/library/article/1000
https://rsjazz.wordpress.com/2013/02/28/setting-up-rational-team-concert-for-api-development/
https://jazz.net/wiki/bin/view/Main/CustomPreconditionsTable
But I have some doubts yet.
I have created a plugin project with extension point ID: com.ibm.team.scm.server.deliver and a java class, but I don't know how to get the path of the files included in the deliver for analyzing them:
import org.eclipse.core.runtime.IProgressMonitor;
import com.ibm.team.process.common.IProcessConfigurationElement;
import com.ibm.team.process.common.advice.AdvisableOperation;
import com.ibm.team.process.common.advice.IAdvisorInfoCollector;
import com.ibm.team.process.common.advice.runtime.IOperationAdvisor;
import com.ibm.team.repository.common.TeamRepositoryException;
import com.ibm.team.repository.service.AbstractService;
public class CheckBadCharacterAdvisor extends AbstractService implements IOperationAdvisor{
#Override
public void run(AdvisableOperation operation,
IProcessConfigurationElement advisorConfiguration,
IAdvisorInfoCollector collector, IProgressMonitor monitor)
throws TeamRepositoryException {
Object data = operation.getOperationData();
// what else here?
}
}
How could I get the change sets included in the delivery?
or
What javadoc or steps do you follow for getting this information?
I don't have the reputation for all the links yet....
These posts show some SCM API that you should look at, in order to approach your problem:
https://rsjazz.wordpress.com/2013/10/15/extracting-an-archive-into-jazz-scm-using-the-plain-java-client-libraries/
http://thescmlounge.blogspot.de/2013/08/getting-your-stuff-using-rtc-sdk-to-zip.html
Unfortunately the answers are in the wrong order...
And more posts I have found useful for RTC SCM API:
https://rsjazz.wordpress.com/2014/09/02/reading-and-writing-files-directly-from-and-to-an-rtc-scm-stream/
this page has pointer to more API examples that could come in handy as well: https://rsjazz.wordpress.com/interesting-links/
I have been relatively successful to find usage in the RTC SDK using PluginSpy, YARI as well as simply the Java Search e.g. for references of classes or methods I found. Sometimes just guessing a method name and search with asterisk helps a lot.
Good luck with your efforts.
I have only done a little bit with the SCM APIs. Here is an example for an Advisor. The most part is common the a follow up action/participant, so this could be a good starter. https://rsjazz.wordpress.com/2012/11/01/restrict-delivery-of-changesets-to-workitem-types-advisordelivery-of-changesets-associated-to-wrong-work-item-types-advisor/
You want to use com.ibm.team.scm.service.internal.AbstractScmService instead of the AbstractService, because it is the entry-point into the SCM API.
I am new to Java (and programming in general) so I thought that making a simple test case applet would help to form a basic understanding of the language.
So, I decided to make a basic applet that would display a green rectangle. The code looks like:
import javax.swing.JApplet;
import java.awt.Color;
import java.awt.Graphics;
public class Box extends JApplet{
public void paint(Graphics page){
page.setColor(Color.green);
page.fillRect(0,150,400,50);
}
}
The HTML file (test.html) that I then embedded that into looks like:
<html>
<body>
<applet code="Box", height="200" width="400">
</applet>
</body>
</html>
I then compiled/saved the Java bit, and put the two into the same folder. However, when I attempt to view the html file, all I see is an "Error. Click for details" box. I tested this in both the most current version of Fire Fox and Opera, and too did I make sure that the Java plug-in was enabled and up to date for both.
So what exactly am I forgetting to do here?
It seems as if everything is close to OK.
Once the .class file is in the same folder as your HTML file it should come up. Your code might contain a typos (comma after "Box").
Example :
<Applet Code="MyApplet.class" width=200 Height=100>
See also :
http://www.echoecho.com/applets01.htm
#Juser1167589 I hope your not still having issues with this, but if you are, try going into your program files, delete the JAVA folder, then redownload java from the big red button on 'java.com'. If there is no JAVA folder then * FACEPALM * GO DOWNLOAD JAVA. another possible answer to why you were seeing the errors on the other sites is that they might not have the required resources to run it anymore.
Applets are not a good place to start.
They are a very old technology and really not very widely used compared to other parts of the Java technology stack.
If you're new to programming in general, I really wouldn't start with applets.
Instead, you should try learning basic programming and Java by building some simple console apps. I've added some general comments about how to do this. After your confidence rises, you can then start worrying about adding extra complexity, applets etc.
First of all download an IDE. Eclipse is one obvious choice (there are also NetBeans and IntelliJ). All modern developers work within an IDE - don't be tempted to try to muddle through without one.
Then, you should have a "scratchpad" - a class where you can try out some simple language features. Here's one which might be useful:
package scratch.misc;
public class ScratchImpl {
private static ScratchImpl instance = null;
// Constructor
public ScratchImpl() {
super();
}
/*
* This is where your actual code will go
*/
private void run() {
}
/**
* #param args
*/
public static void main(String[] args) {
instance = new ScratchImpl();
instance.run();
}
}
To use this, save this as a .java file. It can be a template for other simple experiments with Java. If you want to experiment with a language feature (inheritance, or polymorphism, or collections or whatever you want to learn) - then copy the template (use the copy and rename features inside your IDE, rather than manually copying the file and changing the type names) to a new name for your experiment.
You may also find some of my answer here to be useful.