I wrote a program where I should draw some stuff whenever a key is pressed.
The drawing is done whenever the key is pressed but can be seen only when i resize the window..
public void keyPressed(KeyEvent e) {
Graphics2D g2 = image.createGraphics();
if(e.getKeyCode()==37)
{
System.out.println("left is pressed");
key=LEFT;
sp.SnakeMove(key);
}
if(e.getKeyCode()==38)
{
System.out.println("up is pressed");
key=UP;
sp.SnakeMove(key);
}
if(e.getKeyCode()==39)
System.out.println("right is pressed");
if(e.getKeyCode()==40)
System.out.println("down is pressed");
}
});
.........
.......
public void SnakeMove(int key)
{
//revalidate();
//repaint();
int x1,y1;
System.out.println("key=="+key);
String str;
Graphics2D g2 = image.createGraphics();
switch(key){
case LEFT:
str="--";
g2.drawString(str, 40, 150);
g2.drawRect(10,10,100,100);
System.out.println("String drawn");
revalidate();
break;
case UP:
str="|";
g2.drawString(str, 45, 150);
System.out.println("String drawn");
revalidate();
break;
}//end if switch
repaint();
}//end of snakeMove function