M
Martijn Mulder
I try to load an image into a BufferdImage instance in the constructor
of my class. It does not work. However, if I load the image in the
paint() method, all goes well. How can I fix this?
The code below should compile readily and illustrate the problem. The file
"Dog.jpg" is a file I have on my system. The second line in the constructor
does not do the job. But the same line in the paint()-method (commented out),
makes the picture appear on the screen.
Is there a better way to load an image into a BufferedImage instance?
/*
DisplayImage.java
Load an image into a BufferedImage and display it to the screen
*/
//class DisplayImage
public class DisplayImage extends javax.swing.JFrame
{
//data member image
java.awt.Image image;
//data member displayimage
java.awt.image.BufferedImage displayimage=new
java.awt.image.BufferedImage(377,233,
java.awt.image.BufferedImage.TYPE_INT_ARGB);
//data member graphics2d
java.awt.Graphics2D graphics2d=displayimage.createGraphics();
//constructor
DisplayImage()
{
image=java.awt.Toolkit.getDefaultToolkit().getImage("Dog.jpg");
graphics2d.drawImage(image,0,0,this);
}
//paint
public void paint(java.awt.Graphics a)
{
java.awt.Graphics2D b=(java.awt.Graphics2D)a;
// graphics2d.drawImage(image,0,0,this);//uncommenting this makes it work
b.drawImage(displayimage,0,0,this);
}
static void main(String[]a)
{
DisplayImage displayimage=new DisplayImage();
displayimage.setSize(377,233);
displayimage.show();
}
}
of my class. It does not work. However, if I load the image in the
paint() method, all goes well. How can I fix this?
The code below should compile readily and illustrate the problem. The file
"Dog.jpg" is a file I have on my system. The second line in the constructor
does not do the job. But the same line in the paint()-method (commented out),
makes the picture appear on the screen.
Is there a better way to load an image into a BufferedImage instance?
/*
DisplayImage.java
Load an image into a BufferedImage and display it to the screen
*/
//class DisplayImage
public class DisplayImage extends javax.swing.JFrame
{
//data member image
java.awt.Image image;
//data member displayimage
java.awt.image.BufferedImage displayimage=new
java.awt.image.BufferedImage(377,233,
java.awt.image.BufferedImage.TYPE_INT_ARGB);
//data member graphics2d
java.awt.Graphics2D graphics2d=displayimage.createGraphics();
//constructor
DisplayImage()
{
image=java.awt.Toolkit.getDefaultToolkit().getImage("Dog.jpg");
graphics2d.drawImage(image,0,0,this);
}
//paint
public void paint(java.awt.Graphics a)
{
java.awt.Graphics2D b=(java.awt.Graphics2D)a;
// graphics2d.drawImage(image,0,0,this);//uncommenting this makes it work
b.drawImage(displayimage,0,0,this);
}
static void main(String[]a)
{
DisplayImage displayimage=new DisplayImage();
displayimage.setSize(377,233);
displayimage.show();
}
}