When I tried to to create an image I was using this line but got no images, just blank lines.
g.drawImage(getImage(getDocumentBase(), "Piece_1.png"),coorx,
coory, SIZE_Y / 8, SIZE_Y / 8, this);
How do you display an image and where do you put it in an eclipse project?
Eclipse IDE executes the programs from the src directory. These steps solved me this problem.
Create a new package called resources. You can name it whatever you want.
Add your image files into that package.
Now first load your image before drawing it.
public Image getImage(String name){
URL imgUrl = getClass().getClassLoader().getResource("resources/"+name);
ImageIcon icon = new ImageIcon(imgUrl);
return icon.getImage();
}
An Example
The constructor you can have.
Image piece1;
public Checkers(){
piece1 = getImage("Piece_1.png");
}
public void paint(Graphics g){
if (piece1!=null){
g.drawImage(piece1, xcoord, ycoord, null);
}
}
Hope this solves your problem.
Related
I am having trouble setting images in my newest game. When I call the method getImage(String), and I get the Image like so:
Image head = getImage("Torso_model_01.png");
I get the following error message:
Err: java.lang.NullPointerException
At PB2Main.Body(Body.java : 27)
...
and so on...
On this tutorial, it explains how to get an image using ImageIcon like so:
String imgFile = "Images/" + img;
URL imgURL = getClass().getClassLoader().getResource(imgFile);
ImageIcon imageIcon;
Image image;
if(imgURL != null){
imageIcon = new imageIcon(imgURL);
image = imageIcon.getImage();
}
final Image anImage = image;
I made a method for this:
public URL getURL(String img){
String imgFile = "Images/" + img;
URL imgURL = getClass().getClassLoader().getResource(imgFile);
return imgURL;
}
Then I made a method called getImage(String)
public Image getImage(String img) {
ImageIcon imageIcon;
Image image;
URL imgURL = getClass().getClassLoader().getResource(getURL(img));
if(imgURL != null){
imageIcon = new ImageIcon(imgURL);
image = imageIcon.getImage();
return image;
}
System.err.println("Unable to Locate Image: " + imgURL);
}
Now, I have a class called Body.
In that class, I have a constructor:
public Body(float x, float y, String head, String torso){//atm this is just so i can get the image to actually draw on the screen
Image Head = debugger.getImage(head);// debugger doubles as a library and debugger
//i also can't have this class extend debugger otherwise it will create a window :/
// is that a glitch or something in Java? :L perhaps i just don't understand
// inheritance very well and what happens exactly when you inherit a class :(
Image Torso = debugger.getImage(torso);
g2.drawImage(Head, canvas.geWidth()/ 2,canvas.getHeight()/2, null)// canvas: the window to
//draw to
// can someone also quickly explain in their answer what an image observer is please?
g2.drawImage(Torso, Head.getX() - 5, Head.getY() - 5, null);
}
The compiler gives me the following error message:
java.lang.NullPointerException
At PlazmaBurst2.Body(Body.java: 37)
//the code it brings me to is line 1 in the constructor:
/* null: */ Image Head = debugger.getImage(img);
I don't understand where this NullPointerException is coming from. I did it exactly how they do it in the Custom Graphics Programming section of the same site.
The code works fine if I just copy and paste the code, but not if I use the method getImage(String).
You're problem is on line 3 of getImage(String):
URL imgURL = getClass().getClassLoader().getResource(getURL(img));
This should be changed to:
URL imgURL = getURL(img);
I want to display an image icon in my applet.I created a package resources and saved my image in it.This is what i tried :-
Image logo;//I declare globally
logo = getImage("logo.jpg");//I initialize in the constructor
And i use this proceedure
public Image getImage(String name){
URL imgUrl = getClass().getClassLoader().getResource("resources/"+name);
ImageIcon icon = new ImageIcon(imgUrl);
return icon.getImage();
}
public void paint(Graphics g)
{
if (logo!=null){
g.drawImage(logo, 30, 30, null);
}
g.drawString("Hwllo", 12, 12);
}
Then i call the:
repaint() //In the Constructor
But i dont see an image or my String.What might be the problem.Moreover is there any easier method to load images in the Applet??
You setting the URL to the
URL imgUrl = getClass().getClassLoader().getResource("resources/"+name);
ImageIcon icon = new ImageIcon(imgUrl);
But while Calling paint method, you are calling the logo variable
g.drawImage(logo, 30, 30, this);
The problem is in your setting URL value, set URL to your logo variable like
URL url = new URL(/*Your resources herre*/, /*Your file name here*/);
logo=getImage(url);
After that display image using paint method.
I am trying to load an image and set to background, but i get the error at selectionPanel method "Could not load background image".
It seems that something is going wrong with the image processing but i cant find out what.
public class selectionPanel extends JPanel
{
//Variable with the name of our pic
private static final String path = "selbkgrnd.jpg";
private ImageIcon imageIcon;
private Dimension windowSize;
private int imageHeight;
private int imageWidth;
protected selectionPanel()
{
this.imageIcon = new ImageIcon("selbkgrnd.jpg"); //Save image to imageIcon
Image image = this.imageIcon.getImage();
this.imageWidth = image.getWidth(null);
this.imageHeight = image.getHeight(null);
if ((this.imageWidth == -1) || (this.imageHeight == -1)) //Check if background image is succesfully loaded
{
JOptionPane.showMessageDialog(JOptionPane.getDesktopPaneForComponent(this), "Could not load background image", "Fatal error!", 0);
System.exit(-1);
}
this.windowSize = new Dimension(this.imageWidth, this.imageHeight);
}
protected void startScreen()
{
setOpaque(false);
setSize(this.windowSize);
}
protected int getImageHeight()
{
return imageHeight;
}
protected int getImageWidth()
{
return imageWidth;
}
#Override
public void paintComponent(Graphics g)
{
g.drawImage(this.imageIcon.getImage(), 0, 0, null);
super.paintComponent(g);
}
}
Usually this is due to your looking in the wrong location for your Image File. Try using the complete path to the image, either that or a path relative to the user's directory which can be found with:
System.out.println("user directory: " + System.getProperty("user.dir"));
Edit
You state:
Thank you it worked with the full path, but isnt it supposed to work with just the image name if it is inside the source code folder ?
No. Again, Java will look for the file relative to the user directory.
Note however that if the image is in the class file directory or in a directory relative to this and you make a jar file out of this and need to access the images, then you can't use files. You will need to get the images as a resource and the relative path will be different since it won't be related to the user.dir but rather will be relative to the location of the class files.
I imported an image into Eclipse, in the same package as this class:
public class mainWindow extends JFrame {
public mainWindow() {
Image bg = // \mainPackage\ShittyPlane.png;
Graphics2D g2d;
this.setSize(500,500);
this.setResizable(false);
this.setTitle("GameTest");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
g2d.drawImage(bg, 0, 0, null);
}
}
How do I define the image path?
If the image is part of you source and is packed into jar later for distribution i would sucgest you get a stream to the image using getResourceAsStream.
ClassLoader cl = getClass().getClassLoader();
InputStream is = cl.getResourceAsStream("mainPackage/ShittyPlane.png");
BufferedImage image = ImageIO.read(is);
this aproache will also work in if you run the program from your IDE
If you plan to locate the image using a a File chooser then go with #Pescis's answer.
What you need to do to load an image from a specific file is:
BufferedImage img = null;
try {
img = ImageIO.read(new File("src/mainPackage/ShittyPlane.png")); //I'm guessing this is the path to your image..
} catch (IOException e) {
}
For more info you can read the javadoc on working with images.
I would like to write a program in java...
I want to set the shape of the window(a JFrame) to a set of PNG Images(with a transparent background).
(Actually, I would like to make the window change its shape continual, and it look like an animation!)
And, I read images from files,save them to a array, then, I use class GeneralPath to get the area of my animated character(in png images), save it to areaArray.
After all things are done, I start the paint thread. It works well...But sometimes the window would flash(ah...I mean a flicker happened, but the background color I saw when flashing is transparent, I could saw my desktop wallpaper!).
I don't want to see the flicker/flash again, would someone help me? Thanks!
P.S. : Sorry for my poor English!
public class JCustomFrame extends JFrame implements Runnable
{
private final int max_frame=18; //Here is the max numbers of my png images
private BufferedImage[] BufImageArray; //The array to save all the png images
private BufferedImage nowImage; //Save the image to be drawn in this turn
private int counter; //Indicate which png image to be drawn
private Area[] areaArray; //Save the shapes of the animated character in each png image
public void run()// a thread function to paint the frame continual
{
while(true){
if(counter==max_frame)counter=0;
nowImage=BufImageArray[counter];
setShape(areaArray[counter]);
repaint();
try{
Thread.sleep(100);
}catch(InterruptedException e){
System.out.println("Thread.sleep error!");
}
counter++;
}
}
public JCustomFrame()
{
super();
setUndecorated(true);
setBackground(new Color(0,0,0,0));
counter= 0;
//...some codes here
new Thread(this).start();
}
public void paint(Graphics graphic)
{
graphic.drawImage(nowImage,0,0,this);
}
}
Here is a sample code to run the program:
import javax.swing.*;
public class MainFrame
{
public static void main(String[] args)
{
JCustomFrame myFrame = new JCustomFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(300,400);
myFrame.setVisible(true);
return ;
}
}
I modified 2 lines above, the "png file name" and the "max_frame" to apply the new image files.
I found that if I put the same program on Windows rather than my OpenSuse, it works very well(without the flicker), here I upload all the pack of my source(include the image file).
Here my code is.
Thanks again.
==================================================================================
Thanks Andrew Thompson for suggestions.
This time, I try to delete the codes unrelated to the problem, and paste a gif to show the situation. The codes above isn't runnable, but the source code in the link works well.
P.S. The flicker/flash happened in random frame, isn't completely the same as the gif shows.
('cause I could only add a transparent panel in my gif image at a fixed sequence)
Thanks!!