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.
Related
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 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.
I am currently working on a text-based RPG with a GUI and I can't seem to get the image I want to use to load.
class BackgroundPanel extends Panel
{
// The Image to store the background image in.
Image img;
public BackgroundPanel(String location)
{
// Loads the background image and stores in img object.
img = Toolkit.getDefaultToolkit().createImage(location);
}
public void paintComponent(Graphics g)
{
// Draws the img to the BackgroundPanel.
g.drawImage(img, 0, 0, null);
img.setAccelerationPriority(SCALE_FAST);
}
}
This is the code I use for the panel itself. I tried putting the image file in the root directory of my project but it doesn't seem to help. I have created a folder within the project which I intend to use for all of my images.
I'm not sure what the issue is here. I know I tried using paint() instead of paintComponent(), but then the buttons and other components won't draw until you mouse over them, for some reason.
Any ideas?
I have already posted it at below links in the same context. Please have a look:
ImageIcon does not work with me
How to retrieve image from project folder?
Read image from another directory
It's already described in Oracle Java Tutorial on Loading Images Using getResource
Note: Don't forget to call super.paintComponent() in the overridden paintComponent() method.
I usually load images in Applets using:
this.getImage( getCodeBase(), "myimage.png" );
or
myapplet.getImage( getCodeBase(), "myimage.png" );
But what if I want to load an image from another class which is not a child of Applet, neither does it have a member which refers to the Applet?
Say, I have a sprite class, in whose update method I want to load images for animation:
#Override
public void update(){
frame++;
if ( frame > 3 ) frame = 1;
/* the problem */
loadImage( getCodeBase(), "myimage_" + frame + ".png" );
}
Of course I could include Applet app as parameter, but the sprite's update method gets called in so many different parts of the code and in so many other classes, that it will extremely complicate stuff and make life difficult.
So is there a way I can load an image from a file in an applet without using the applet's getImage() method?
So is there a way I can load an image from a file in an applet without using the applet's getImage() method?
Image img = ImageIO.read(url);
When loading an image from a file in a non-applet class definition or in an application, you need the following statements:
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image1 = toolkit.getImage("fileName.ext");
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")));