Java Applet Image Load - java

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.

Related

Java Constructor with ImageIcon

I created a small program that inserts an ImageIcon (resized in another class) into a JLabel through a constructor
I am struggling to return the icon in the JLabel
Here's my code:
Main Class:
traforma imageObj = new traforma("image1.png"); //traforma is another class
ImageIcon Icon11 = new ImageIcon(imageObj.Icon11);
imageLabel.setIcon(Icon11); //Here he gives me error, he can't find my ' Icon11 '
traforma Class:
public class traforma {
public traforma(String image) {
ImageIcon Icon1 = new ImageIcon(getClass().getClassLoader().getResource(image));
Image image = Icon1.getImage();
Image newimg = image.getScaledInstance(470, 360, java.awt.Image.SCALE_SMOOTH);
ImageIcon Icon11 = new ImageIcon(newimg);
}
Object Icon11 = this.Icon11; // i guess the problem is here
}
I am new to Java,
Hope I have been clear
This code makes no sense:
Object Icon11 = this.Icon11;
The problem is, that the variable "Icon11" that you initialized within the method is not used anywhere. After method completed, it will be thrown away. What you can do, is to assign the created icon object to the member variable, not to the local variable.
Thy style of your code is not perfect: the usage of lower and upper case, the usage of ImageIcon instead of directly loading image, etc. But if we keep it as close to your code as possible and try to do minimal changes, the working code may look as follows:
public class traforma {
public traforma(String image) {
ImageIcon Icon1 = new ImageIcon(getClass().getClassLoader().getResource(image));
Image image = Icon1.getImage();
Image newimg = image.getScaledInstance(470, 360, java.awt.Image.SCALE_SMOOTH);
this.Icon11 = new ImageIcon(newimg);
}
public ImageIcon Icon11;
}

NullPointerException while getting an Image

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);

Can't define a path to an image

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.

Display image on applet

I am using Jtree for listing various images of a directory, I want to display image on applet when the user click on the image name displayed in the Tree, the code i'm using is as below, ta is an object of the applet because i'm using it in another class.
private void displayImage(URL furl, String fname) {
ta.Picture = ta.getImage(furl, fname);
prepareImage(ta.Picture, this);
Graphics g = ta.imageCanvas.getGraphics();
g.clearRect(10, 10, 800, 800);
g.drawImage(ta.Picture, 10, 10, this);
} // displayImage
public void valueChanged(TreeSelectionEvent e)
{
// TODO Auto-generated method stub
FileTreeNode node = (FileTreeNode) tree.getLastSelectedPathComponent();
System.out.println("slecte asldf " + node.isLeaf());
if (node.isLeaf())
{
currentFile = node.file;
System.out.println("File name " + currentFile.getName());
try
{
URL furl = new URL("file:/F:/photos");
displayImage(furl, currentFile.getName());
}
catch (MalformedURLException mle)
{
System.out.println("Exception::::::" + mle);
}
}
else
currentFile = null;
}
But its not working.
As you are showing files from the local filesystem, working with URLs is not required. Use
displayImage(currentFile);
and rewrite that method as following:
private void displayImage(File file) {
BufferedImage image = ImageIO.read(file);
ta.image = image;
ta.repaint();
}
where the paint method of the (I an assuming) component ta must be like
BufferedImage image;
public void paint(Graphics g) {
g.clearRect(10, 10, 800, 800);
g.drawImage(ta.Picture, 10, 10, this);
}
Because of security reasons, the applet will only be able to access the file system if signed or running without security manager (most often on the same computer).
But its not working.
This is in no way helpful, do you get exceptions? What happens? Please post an SSCCE for better help sooner
I want to display image on applet when the user click on the image
name displayed in the Tree, the code i'm using is as below, ta is an
object of the applet because i'm using it in another class.
IMO you are going about it wrong using the JPanel object and Component#getGraphics.
Dont use Component#getGraphics() as its not good practice and not persistent thus on next call to repaint() the screen will be cleared.
Dont use Applet with Swing components rather use JApplet.
Add a custom JPanel with getters and setters for BufferedImage variable to the container and than override paintComponnet and draw the BufferedImage there.
Now to change the BufferedImage simply call the setter i.e setBackgroundImage(BufferedImage img) and than call repaint() on JPanel to show the changes. Like so:
public class MyPanel extends JPanel {
private BufferedImage bg;
public MyPanel(BufferedImage bi) {
bg=bi;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
g2d.drawImage(bg,0,0,this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(bg.getWidth(),bg.getHeight());
}
public BufferedImage setBackgroundImage(BufferedImage bi) {
bg=bi;
}
}
Now we use it like so:
MyPanel mp=new MyPanel(...);//create the panel with an image
...
add(mp);//add to container
...
mp.setBackgroundImage(..);//change the image being displayed
mp.repaint();//so the new image may be painted

adding images to a java applet?

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.

Categories

Resources