I am having problems with my new Java applet.
public Speler() {
this.x = 10;
this.y = 470;
hitBox = new Rectangle( x, y, 52, 10 );
spaceShip = new ImageIcon( "images/spaceship.png" );
}
In my project's src folder, I have some .png images which need to be loaded in. In Eclipse AppletViewer this works just fine, however in my browser it does not.
I have already searched the internet and tried signing it, however this didn't help.
Any help would be appreciated, however I just started programming in Java, so I don't know an awful lot!
new ImageIcon( "images/spaceship.png" );
That constructor presumes the String represents a File path. It cannot work for an applet from a web site since a File can only ever point to a resource on the client computer where the applet is running.
For an applet, instead access resources by URL. The URL might be constructed relative to the code base or document base of the applet, or from a Jar on the run-time class-path of the applet. If an applet is digitally signed and declares all-permissions, it can even reach across sites to fetch images, as long as the external site allows hot-linking.
Related
Im making a game with JavaFX and want to load images into it. Im having trouble with finding the correct URL to load the image
Its supposed to be a Memory game and the image is supposed to be loaded into a button for the player to interact with. Normally when I tried working with images, I start the URL at the projects folder and it works fine but here I keep getting error messages. I only get it to work when I type in the full URL from the C: Drive but shouldnt it also be possible to access it just from projects folder?
This is the constructor of the class for the Memory Cards
public MemoryCard(String front, int picID)
{
front = new ImageView(front);
picBack = new ImageView("src/grafics/back.jpg");
setGraphic(picBack);
//...
}
I have created a folder called 'grafics' under the source folder with the correct images inside. I thought this would work but it just gives me the IllegalArgumentException message on the line where I load the image.
I'm trying to create one simple GUI based testing tool in Java using Eclipse. I have been trying to add icon to my application. Images are present inside the project in a folder. Could you please suggest what mistake I'm doing.
I'm used below two ways, unfortunately both are not helping me. -
1.) frame.setIconImage(image).
2.) setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource(Filepath)));
Below is the setup of my project in Eclipse -
Below is code which i'm using -
public static void main(String[] args) {
JFrame frame = new JFrame("Testing Tool");
// setting close operation
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// sets 500 width and 600 height
frame.setSize(500, 600);
try {
Image image = new ImageIcon("/Project_T/Images/biplane.jpg").getImage();
frame.setIconImage(image);
} catch(Exception e) {
System.out.println("Application icon not found");
}
// uses no layout managers
frame.setLayout(null);
// makes the frame visible
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
Since i'm going to create an .exe file for this project using lunach4J, is this the way of keeping files (placing them in a folder of project since I would be using multiple images and files) that ensures the application running on any machine.
This is the code I used with a Swing application packaged in an executable JAR file. The JFrame has the icon image.
private static final String APP_ICON_PATH = "myapp/icondirectory/report.png";
ImageIcon icon = new ImageIcon(ClassLoader.getSystemResource(APP_ICON_PATH));
frame.setIconImage(icon.getImage())
The "myapp" is the root of my package structure; e,g., the GUI class using the frame is in the package myapp.gui package. The image PNG files are within the application's executable JAR file (as you see in the code within a separate folder).
Also, look at the Oracle's Java Swing tutorials explain the usage of icons.
I fiddled a lot and finally found a way out , since my explanation was a bit long so I thought of writing an answer. Also please suggest that is this a good way since we would be exporting our project.
Java gives you the power to change the ICON for your application with the help
of setIconImage(image), but this method is not that direct, since we are
dealing with multiple files those should be present while executing the code so we
would have to ensure that their paths are correct and accessible in order to run smoothly.
Hence we save our files inside the src by creating another folder and from there
we can import the files easily. Follow these steps
Step - 0 - Place the files inside src folder of the project
Put the files inside the scr folder by creating another folder, here I created another folder by the name of images and placed my files there, hence the file path would be
"Images/biplane.png",
please ensure that there are no "/" placed before Images (our folder name)
Step - 1 - Place the file path inside a URL variable
Step - 2(Optional) - Print this URL variable to cross check that this is not null. If this is null check your path again and repeat the activity so that this value is not null.
Step - 3 - Now pass this URL to ImageIcon method.
Step - 4 - Call the setIconImage method with that image.
Code Used -
URL url = test.class.getClassLoader().getResource("Images/biplane.png");
System.out.println("Path for file is :- \"" + url + "\"");
Image image = new ImageIcon(url).getImage();
frame.setIconImage(image);
I'm doing my university project, and it runs on my IDE, but when i try to run it directly from a jar, it doesn't load any images at all. So i created a resources folder in my proyect, but apparently, it's not working, because i'm not sure of how to call them. I already read a lot of posts using the "getClass().getResource()" method, but it's giving me a null pointer exception. Any help guys? I'm leaving my code:
(Btw, it's a megaman game):
public GameObject(int x,int y, int velX,int velY,String archivo){
this.x = x;
this.y = y;
this.velX = velX;
this.velY = velY;
principal = new ArrayList<ImageIcon>();
ImageIcon imagen = new ImageIcon(archivo);
principal.add(imagen);
mono = new JLabel(principal.get(0));
mono.setBounds(this.x,this.y,mono.getIcon().getIconWidth(),mono.getIcon().getIconHeight());
}
This is my main "Sprite" code, i just create other sprites which extends from this class. The "Archivo" variable, it's a string where the .png file is, here i'm putting an example of how i'm calling it:
public MegamanSprite(int x, int y) {
super(x, y, 1, 1, "src/Resources/megamanpd.png");
}
and here it's an image of how i have my folders in my Eclipse project:
I already tried using this:
public GameObject(int x,int y, int velX,int velY,String archivo){
this.x = x;
this.y = y;
this.velX = velX;
this.velY = velY;
principal = new ArrayList<ImageIcon>();
ImageIcon imagen = new ImageIcon(getClass().getResource(archivo));
principal.add(imagen);
mono = new JLabel(principal.get(0));
mono.setBounds(this.x,this.y,mono.getIcon().getIconWidth(),mono.getIcon().getIconHeight());
}
but this is giving me a null pointer exception, and without it it's not. Any help will be really apreciated. Thanks in advance!
You need to get your resource as stream. This will get you an InputStream which you can use to load your image from a jar.
Get the class of your object as a Class using the getClass()
Use the getResourceAsStream() to get an InputStream. Remember, your src folder will disappear in a jar. JB Nizet pointed that out.
Then use ImageIO.read() and pass the InputStream to get back a BufferedImage
BufferedImage is an Image and hence you can cast it to a variable of type Image. So, do that.
ImageIcon has a constructor that has a constructor which accepts an Image.
You are done !
It’s hard to guess when the only thing we have is a screenshot but by looking at your icons I have the suspicion that you Resources folder is excluded from the build path. In this case it is not copied to the bin folder and therefore not accessible by getResource invocations.
Try right-clicking on the Resources folder and choosing “Build Path”→“Include” from the popup menu. The icon should change from a generic folder to a package-like icon (it will look different from packages containing classes though). Then a GameObject.class.getResourceAsStream( "Resources/megamanpd.png"); should work from within Eclipse.
If the build path is set up correctly, generating a jar should get the right default setup but it seems that including the src/Resources/ folder additionally to the bin contents has been added manually. So you might have to fix the setup manually. Regenerating the jar with the default setup should now work to get a jar in which getResource works correctly.
I am trying to display a JPEG image and a moving dot on a Java applet which I am using on a web based application. However, when I run the applet it works fine, but when I display the applet from the JSP page, I get the moving dot but not the JPEG image.
Is there a specific folder where the JPEG needs to be?
These are the 2 methods i use for drawing the picture and the moving dot on the screen.
public class mapplet extends Applet implements Runnable {
int x_pos = 10;
int y_pos = 100;
int radius = 20;
Image img, img2;
Graphics gr;
URL base;
MediaTracker m;
#Override
public void init() {
mt = new MediaTracker(this);
try {
//getDocumentbase gets the applet path.
base = getCodeBase();
img = getImage(base, "picture.jpg");
m.addImage(img, 1);
m.waitForAll();
} catch (InterruptedException ex) {
Logger.getLogger(movement.class.getName()).log(Level.SEVERE, null, ex);
}
public void paint (Graphics g) {
g.drawImage(img, 0, 0, this);
// set color
g.setColor (Color.red);
// paint a filled colored circle
g.fillOval (x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
}
The code one below is the call from the jsp page
<applet archive="mapplet.jar" code="myapplets/mapplet.class" width=350 height=200>
</applet>
The jar file and the picture are in the same folder as the jsp page, and there is also a folder containing the contents of the class and image of the applet in the web section of the application. The applet loads fine however the picture doesn't display. I think it's not the code but the location of the picture that is causing a problem.
Thanks
Yes, the image should be in the same folder as the source code. I would recommend to do a folder called images and inside it put all your images and just change "picture.jpg" to "\images\picture.jpg". Check your website directory to see if the image is in the same folder as the source code.
Some comments that might make it more clear for you.
//getDocumentbase gets the applet path.
No. getDocumentBase() provides the path to the web page. But that is neither here, nor there, since this applet actually calls..
base = getCodeBase();
..which provides the codebase. The codebase defaults to the directory of the web page, unless a codebase parameter is specified in the applet element. Since the applet element declares no codebase, the base will be the same URL as the document base.
BTW: In the applet element
code="myapplets/mapplet.class"
..should be..
code="myapplets.mapplet"
And since common nomenclature for Java class names is EachWordUpperCase, the class name should be changed.
Doe the applet declare?
package myapplets;
BTW (2):
there is also a folder containing the contents of the class and image of the applet in the web section of the application.
What does that mean? Please provide complete paths from the root of the server to all resources (e.g. the HTML/JSP, Jar file & image) used.
please check your path ..or to resolve it please put your files inside a folder and pack it with JAR file.and provide the relative path of image files inside your jar.
Like:
let your applet name is myapp.class in package demoapp
then put your files in dir "images" inside demoapp and provide path relative to this path in all your java code.
dont forget to include image files in jar build.
In my project I have 2 packages.
images - contain images and
notification - contain java files
In notification/main.java I get Image object from image using this code
Image image = Toolkit.getDefaultToolkit().getImage("/images/key-16x16.png");
and I can't get image.
How can I fix this bug.
I'm using Netbeans to develop Java desktop application and I have solved my problem.
Image image = new ImageIcon(this.getClass().getResource("/images/bell-icon16.png")).getImage();
"this" is a class extends JFrame
/ means an absolute path, save Java web-apps where / means relative to context. So, I would suggest to use relative URL, means get rid of that / in front, and then provide the right path.
In case, even then you can't solve it, try to create a file on the same path you are looking for image. This way you will know that where you are looking exactly and where you should look.
You could also try
Image image = new ImageIcon(path).getImage();
Incase the solution above doesn't work, try this (which worked for me):
Image image = Toolkit.getDefaultToolkit().createImage(this.getClass().getResource("/Images/bell-icon16.png"));
i've also been on this and it turns out that you need to create a package inside of your src folder.
for instace if you create a package called images inside of the src folder, your relative path will be
/images/yourimage.png.
Notice that the slash(/) must be there!
more info here http://forums.macrumors.com/showthread.php?t=533922
it worked for me
Toolkit tk = Toolkit.getDefaultToolkit();
Class<? extends JFrame> j = YOURJFRAME.getClass();
Image image = tk.createImage(j.getResource("/images/bell-icon16.png"));
Try that code, if you have a JFrame that will work.
If you have an Applet, then just use
Toolkit tk = Toolkit.getDefaultToolkit();
Image image = tk.createImage("images/bell-icon16.png");
With applets you never want to use the / in the beginning, but if you have a JFrame, and you are using getResource, you need the / in the beginning of the Path.
SwingResourceManager.getImage(YourClass.class,"key-16x16.png");
The getIcon method will return Icon as similar
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("../resources/MainIcon.png")));