Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem with drawImage()

 
pingkan paula
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone

I want to create an image when a button "1" pressed
The code looks like this

public class Test extends Canvas{
public static Graphics g_fx;
private image img;
public Test(){
try{
img=Image.createImage("face.png");
}
}

protected void paint(Graphics g){
g_fy=g;
}
protected void keyPressed(int key){
if(key==49)
g_fy.drawImage(img,50,50,Graphics.LEFT+Graphics.TOP);
}
}

When i run it, it doesn't display anything, although I have test to print something inside keyPressed() method it did displayed in the console, is method drawImage() can't be applied outside the paint() method?
 
Svend Rost
Ranch Hand
Posts: 904
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"repaint" ?

/Svend Rost
 
Jeff Jetton
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, generally, in Java, the reference to the screen's Graphics object (called "g" in this case) is not reliable outside of the paint() method.

Standard procedure is to do all of your drawing in the paint() method, or in methods that are called only by paint(). That drawing code should look at the state of your application to know what to draw.

For example, you could have your key press set a boolean variable. Then, when paint() did its thing, it would look at the variable to know whether or not to draw the image.

And you don't normally call paint() directly. As Svend said, you would usually call repaint().

- Jeff
 
Arun Soman
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check the image size and its dimesions also.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic