m00
asked on
Why did the image go?
This is my code:
import java.awt.* ;
class Test extends Frame
{
Test()
{
add(new Picture()) ;
setSize(600,400) ;
}
public static void main(String args[])
{
new Test().show() ;
}
}
class Picture extends Panel
{
Picture()
{
Toolkit t = getToolkit() ;
Image img = t.getImage("heart.jpg") ;
add(new ImagePanel(img)) ;
}
}
class ImagePanel extends Panel
{
Image img ;
ImagePanel(Image img)
{
this.img = img ;
}
public void paint(Graphics g)
{
g.drawImage(img,310,370,th is) ;
}
}
Why doesn't this draw the image? I'm using jdk 1.2.2.
import java.awt.* ;
class Test extends Frame
{
Test()
{
add(new Picture()) ;
setSize(600,400) ;
}
public static void main(String args[])
{
new Test().show() ;
}
}
class Picture extends Panel
{
Picture()
{
Toolkit t = getToolkit() ;
Image img = t.getImage("heart.jpg") ;
add(new ImagePanel(img)) ;
}
}
class ImagePanel extends Panel
{
Image img ;
ImagePanel(Image img)
{
this.img = img ;
}
public void paint(Graphics g)
{
g.drawImage(img,310,370,th
}
}
Why doesn't this draw the image? I'm using jdk 1.2.2.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I use MediaTracker because I want to have the loaded Image before I start using it.
try this code
Image img = t.getImage("d:/1.jpg") ;
System.out.println("width: " + img.getWidth(null));
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(img, 11);
try {tracker.waitForID(11);} catch (Exception e ) {e.printStackTrace();}
System.out.println("width: " + img.getWidth(null));
and you will see something like
-1
320
I want to load th image explicitely because I won't be able to calculate the real Preferred Size
>> d = new Dimension(img.getWidth(nul l), img.getHeight(null));
try this code
Image img = t.getImage("d:/1.jpg") ;
System.out.println("width:
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(img, 11);
try {tracker.waitForID(11);} catch (Exception e ) {e.printStackTrace();}
System.out.println("width:
and you will see something like
-1
320
I want to load th image explicitely because I won't be able to calculate the real Preferred Size
>> d = new Dimension(img.getWidth(nul
you can code even without MediaTracker ...
the real problem in your code is that the (because you do not explicitly set coordinates or use some layout manager) ImagePanel probably has size (0 x 0)
put this line inside its paint() method.
System.out.println("" + getBounds());
btw. if it really has size(0 x 0) its paint() method won't be even invoked from the framework.
the real problem in your code is that the (because you do not explicitly set coordinates or use some layout manager) ImagePanel probably has size (0 x 0)
put this line inside its paint() method.
System.out.println("" + getBounds());
btw. if it really has size(0 x 0) its paint() method won't be even invoked from the framework.
ASKER
Thanks for your great explanation!
ASKER