I am teaching myself how to use images in Eclipse.
I am trying to get my code implementing images to compile:
import java.awt.*;
import javax.swing.JFrame;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageDemo extends Canvas
{
Image coolFace;
public ImageDemo() throws Exception
{
coolFace = ImageIO.read( new File("jesus.png") );
}
public void paint( Graphics g )
{
// Image , x, y, this
g.drawImage(coolFace,100,100,this);
g.setColor( Color.yellow );
g.drawOval(88,88,70,25);
}
public static void main(String[] args) throws Exception
{
JFrame win = new JFrame("Image Demo");
win.setSize(1024,768);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.add( new ImageDemo() );
win.setVisible(true);
}
}
The problem is that I do not know how to get my image in the same source folder of my code in Eclipse.
I think I created one but I do not know how to put an image from my Desktop there.
Any help would be appreciated.
Generally eclipse starts jvm with current directory from base of the project so place it on base of the project to read it with existing code
Related
Recently i decided to start learning how to make 2D games With JAVA ( eclipse ) so i found a tutorial online that shows how to make superMari game with java, i wrote the same code he wrote and i followed step by step what he did, which wasn't a big thing to talk about, unfortunately he's code shows, after excuting, a window with two images in it while mine shows just the window with no images, i ensure you that i imported the two images and put them in one package to avoid all kind of problems but it still shows nothing.
my code has two classes, "main" and "Scene", here it is, hopefully someone will find a solution for me, thank you guys!
Main.java :
package AiMEUR.AMiN.jeu;
import javax.swing.JFrame;
public class Main {
public static Scene scene;
public static void main(String[] args) {
JFrame fenetre = new JFrame("Naruto in mario World!!");
fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fenetre.setSize(700, 360);
fenetre.setLocationRelativeTo(null);
fenetre.setResizable(false);
fenetre.setAlwaysOnTop(true);
scene = new Scene();
fenetre.setContentPane(scene);
fenetre.setVisible(true);
}
}
Scene.java :
package AiMEUR.AMiN.jeu;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Scene extends JPanel{
private ImageIcon icoFond;
private Image imgFond1;
private ImageIcon icoMario;
private Image imgMario;
private int xFond1;
public Scene(){
super();
this.xFond1 = -50;
icoFond = new ImageIcon(getClass().getResource("/Images/fond.gif"));
this.imgFond1 = this.icoFond.getImage();
icoMario = new ImageIcon(getClass().getResource("/Images/1.png"));
this.imgMario = this.icoMario.getImage();
// paintComponent(this.getGraphics());
}
public void paintCompenent(Graphics g){
super.paintComponent(g);
Graphics g2 = (Graphics2D)g;
g2.drawImage(this.imgFond1, this.xFond1, 0, null);
g2.drawImage(imgMario, 300, 245, null);
}
}
You have not named the paintComponent method correctly, and therefore it is not being overridden.
The correct name is paintComponent not paintCompenent:
public class Example extends JPanel {
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
}
}
You can determine the loading status of an ImageIcon by doing something like this:
public Scene(){
super();
this.xFond1 = -50;
icoFond = new ImageIcon(getClass().getResource("/Images/fond.gif"));
int status = icoFond.getImageLoadStatus();
switch (status) {
case (MediaTracker.COMPLETE): {
System.out.println("icoFond image has successfully loaded");
}
case (MediaTracker.ERRORED): {
System.out.println("The icoFond image didn't load successfully");
// probably because the image isn't actually at "/Images/fond.gif"
}
}
this.imgFond1 = this.icoFond.getImage();
icoMario = new ImageIcon(getClass().getResource("/Images/1.png"));
this.imgMario = this.icoMario.getImage();
// paintComponent(this.getGraphics());
}
Hello all So I'm making progress on my animation program but I'm running into a problem where my alien.png isn't showing up in the jframe. I have the alien.png in the same folder as this animation demo.java so I'm not sure why its not finding the alien.png. Any help would be appreciated
package animationdemo;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class AnimationDemo extends JFrame {
Image alien;
public AnimationDemo() {
alien = Toolkit.getDefaultToolkit().getImage("alien.png");
MovingMessagePanel messagePannel = new MovingMessagePanel();
messagePannel.alien = this.alien;
Timer timer = new Timer(50, messagePannel);
timer.start();
this.add(messagePannel);
}
public static void main(String[] args) {
AnimationDemo frame = new AnimationDemo();
frame.setTitle("Project 10");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
class MovingMessagePanel extends JPanel implements ActionListener {
public int xCoordinate = 20;
public int yCoordinate = 20;
public int xDir=5;
public int yDir=5;
public Image alien;
public void actionPerformed(ActionEvent e) {
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (xCoordinate > getWidth()) xDir*=-1;
if (yCoordinate > getHeight()) yDir*=-1;
if (xCoordinate <0) xDir*=-1;
if (yCoordinate <0) yDir*=-1;
xCoordinate += xDir;
yCoordinate += yDir;
g.drawImage(alien,xCoordinate,yCoordinate,this);
}
}
Let's look at the code lines:
package animationdemo; // this one!
import java.awt.Graphics;
// ..
public class AnimationDemo extends JFrame {
Image alien;
public AnimationDemo() {
alien = Toolkit.getDefaultToolkit().getImage("alien.png"); // & this one!
That last line is effectively trying to load a File from the 'current directory'.
But the image probably won't be accessible as a File any longer. Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An embedded-resource must be accessed by URL rather than file. See the info. page for embedded resource for how to form the URL.
Note given the first highlit line, the best path for finding the resource would presumably be:
..getResource("/animationdemo/alien.png")
Note also that the getResource method is case sensitive, so ..
..getResource("/animationdemo/alien.PNG")
.. won't find the lower case version, nor vice-versa.
As an aside, I did a check of my 'missing image' theory by making this small change to the source above:
alien = new BufferedImage(40, 40, BufferedImage.TYPE_INT_RGB);
//Toolkit.getDefaultToolkit().getImage("alien.png");
Given I saw an animated black square, it supports the major problem is that the image is not being found. The code still has a few other aspects that should be tweaked, but it is basically going in the right direction.
I am having a error for my GUI. Trying to set title bar icon then be included in a Runnable JAR.
BufferedImage image = null;
try {
image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));
}
catch (IOException e) {
e.printStackTrace();
}
frame.setIconImage(image);
Here is the error I am getting:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at GUI.<init>(GUI.java:39)
at GUI.main(GUI.java:351)
The image is in the correct directory which "resources" folder is the root of the
project file
First of all, change this line :
image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));
to this :
image = ImageIO.read(getClass().getResource("/resources/icon.gif"));
More info, on as to where lies the difference between the two approaches, can be found on this thread - Different ways of loading a Resource
For Eclipse:
How to add Images to your Resource Folder in the Project
For NetBeans:
Handling Images in a Java GUI Application
How to add Images to the Project
For IntelliJ IDEA:
Right-Click the src Folder of the Project. Select New -> Package
Under New Package Dialog, type name of the package, say resources. Click OK
Right Click resources package. Select New -> Package
Under New Package Dialog, type name of the package, say images. Click OK
Now select the image that you want to add to the project, copy it. Right click resources.images package, inside the IDE, and select Paste
Use the last link to check how to access this file now in Java code. Though for this example, one would be using
getClass().getResource("/resources/images/myImage.imageExtension");
Press Shift + F10, to make and run the project. The resources and images folders, will be created automatically inside the out folder.
If you are doing it manually :
How to add Images to your Project
How to Use Icons
A Little extra clarification, as given in this answer's first
code example.
QUICK REFERENCE CODE EXAMPLE(though for more detail consider, A little extra clarification link):
package swingtest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 7/1/14
* Time: 9:44 AM
* To change this template use File | Settings | File Templates.
*/
public class ImageExample {
private MyPanel contentPane;
private void displayGUI() {
JFrame frame = new JFrame("Image Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new MyPanel();
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private class MyPanel extends JPanel {
private BufferedImage image;
public MyPanel() {
try {
image = ImageIO.read(MyPanel.class.getResource("/resources/images/planetbackground.jpg"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return image == null ? new Dimension(400, 300): new Dimension(image.getWidth(), image.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new ImageExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
There's a much easier way to load and set an image as a frame icon:
frame.setIconImage(
new ImageIcon(getClass().getResource("/resources/icon.gif")).getImage());
And thats all :)! You don't even have to use a try-catch block because ImageIcon does not throw any declared exceptions. And due to getClass().getResource(), it works both from file system and from a jar depending how you run your application.
If you need to check whether the image is available, you can check if the URL returned by getResource() is null:
URL url = getClass().getResource("/resources/icon.gif");
if (url == null)
System.out.println( "Could not find image!" );
else
frame.setIconImage(new ImageIcon(url).getImage());
The image files must be in the directory resources/ in your JAR, as shown in How to Use Icons and this example for the directory named images/.
I am working on a java game and the game works perfectly in eclipse, but when I exported is as a runnable jar file it did not work. Only a black window showed up.
My game has a splash screen which changes to menu screen after few seconds. the splash screen sconsists of an BufferedImage (in jpg) but the menu screen also consists of a Graphics2D writing. Few seconds after running the jar file the writing doesn't show up, so I think image formats and such might not be the issue.
I'm quite confused and frustrated so any help would be appriciated.
It turned out the problem is in my use of Timer, this is my source of the splashscreen
package GameState;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Timer;
import Main.GamePanel;
public class SplashState extends GameState implements ActionListener{
private BufferedImage image;
private Timer timer;
public SplashState(GameStateManager gsm) {
this.gsm = gsm;
try {
image = ImageIO.read(new File("Resources/Backgrounds/block.jpg"));
timer = new Timer(2000, this);
timer.setRepeats(false);
timer.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void init() {
}
public void update() {
}
public void draw(Graphics2D g) {
g.drawImage(image, (GamePanel.WIDTH-image.getWidth())/2, (GamePanel.HEIGHT-image.getHeight())/2, null);
}
public void keyPressed(int k) {
}
public void keyReleased(int k) {}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
gsm.setState(GameStateManager.MENUSTATE);
timer.stop();
}
}
I still don't know what's wrong so any help would be appriciated
I've had a similar problem in the past, and it was due to the way Eclipse was packaging the required libraries into the jar. I would bet you have it set to "Extract required libraries into generated jar", and you should set it to "Package required libraries into generated jar". To do this, right click on project -> Export -> Java -> Runnable Jar File. Then click next, and select the radio button for "Package required libraries into generated jar". This should fix your problem.
If you are writing to an image, the image must be outside of the jar file, because you cannot edit a jar file while it is running. If this is the case, you may want to make a folder that contains your jar and the images it will write to.
I have an image and I want to display it in the applet, The problem is the image wont display. Is there something wrong with my code?
Thanks...
Here's my code :
import java.applet.Applet;
import java.awt.*;
public class LastAirBender extends Applet
{
Image aang;
public void init()
{
aang = getImage(getDocumentBase(), getParameter("images.jpg"));
}
public void paint(Graphics g)
{
g.drawImage(aang, 100, 100, this);
}
}
aang = getImage(getDocumentBase(), getParameter("images.jpg"));
I suspect you are doing something wrong, and that should be just plain:
aang = getImage(getDocumentBase(), "images.jpg");
What is the content of HTML/applet element? What is the name of the image? Is the image in the same directory as the HTML?
Update 1
The 2nd (changed) line of code will try to load the images.jpg file in the same directory as the HTML.
Of course, you might need to add a MediaTracker to track the loading of the image, since the Applet.getImage() method returns immediately (now), but loads asynchronously (later).
Update 2
Try this exact experiment:
Save this source as ${path.to.current.code.and.image}/FirstAirBender.java .
/*
<applet class='FirstAirBender' width=400 height=400>
</applet>
*/
import javax.swing.*;
import java.awt.*;
import java.net.URL;
import javax.imageio.ImageIO;
public class FirstAirBender extends JApplet {
Image aang;
public void init() {
try {
URL pic = new URL(getDocumentBase(), "images.jpg");
aang = ImageIO.read(pic);
} catch(Exception e) {
// tell us if anything goes wrong!
e.printStackTrace();
}
}
public void paint(Graphics g) {
super.paint(g);
if (aang!=null) {
g.drawImage(aang, 100, 100, this);
}
}
}
Then go to the prompt and compile the code then call applet viewer using the source name as argument.
C:\Path>javac FirstAirBender.java
C:\Path>appletviewer FirstAirBender.java
C:\Path>
You should see your image in the applet, painted at 100x100 from the top-left.
1) we living .. in 21century, then please JApplet instead of Applet
import java.awt.*;
import javax.swing.JApplet;
public class LastAirBender extends JApplet {
private static final long serialVersionUID = 1L;
private Image aang;
#Override
public void init() {
aang = getImage(getDocumentBase(), getParameter("images.jpg"));
}
#Override
public void paint(Graphics g) {
g.drawImage(aang, 100, 100, this);
}
}
2) for Icon/ImageIcon would be better to look for JLabel
3) please what's getImage(getDocumentBase(), getParameter("images.jpg"));
there I'll be awaiting something like as
URL imageURL = this.getClass().getResource("images.jpg");
Image image = Toolkit.getDefaultToolkit().createImage(imageURL);
Image scaled = image.getScaledInstance(100, 150, Image.SCALE_SMOOTH);
JLabel label = new JLabel(new ImageIcon(scaled));
Well , above answers are correct. This is the code I used to display image. Hope it helps:
/*
<applet code = "DisplayImage.class" width = 500 height = 300>
</applet>
*/
import java.applet.Applet;
import java.awt.*;
public class DisplayImage extends Applet
{
Image img1;
public void init(){
img1 = getImage(getCodeBase(),"Nature.jpg" );
}
public void paint(Graphics g){
g.drawImage(img1, 0,0,500,300,this);
}
}
In above code, we create an image class object and get image from location specified by codebase. Then plot the image using drawImage method. Those who are interested in knowing value of getCodeBase() and getDocumentBase() methods can add following code in paint method. They are actually location of src folder in your project folder:-
String msg;
URL url=getDocumentBase();
msg="Document Base "+url.toString();
g.drawString(msg,10,20);
url=getCodeBase();
msg="Code Base "+url.toString();
g.drawString(msg,10,40);
One more point to note:- Make sure images and classes don't have same name in src folder. This was preventing my image to be displayed.