I want to move an Image ( here is rectangle ) in applet, applet draws it, but I wonder why the image is not moving? there is no compile error!
here is my code:
package game;
import java.awt.*;
import javax.swing.*;
import java.applet.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Gamer extends JApplet implements KeyListener
{
private int x=50,y=50;
@Override
public void init( )
{
addKeyListener(this);
}
@Override
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
switch( keyCode )
{
case KeyEvent.VK_UP:
if( y>0 ) //when up key is pressed and the position of the player is not on the edge
{
y=y-19;
repaint();
}
break;
case KeyEvent.VK_DOWN:
if( y<171 ) //when down key is pressed and the position of the player is not on the edge
{
y=y+19;
repaint();
}
break;
case KeyEvent.VK_LEFT:
if( x>0 )
{
x=x-15;
repaint();
}
break;
case KeyEvent.VK_RIGHT:
if( x<285 )
{
x=x+15;
repaint();
}
break;
}
}
@Override
public void paint( Graphics g ) //will draw the background and the character
{
g.fillRect(x, y, 200, 200);
}
@Override
public void keyReleased(KeyEvent arg0)
{
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0)
{
// TODO Auto-generated method stub
}
}
When I pressed my up/down/left/write arrow , the rectangle is not moving . Please explain why ? T.I.A.
The problem is that your applet doesn't catch the KeyEvent
, so your paint method does not get called.
In fact there is an issue when you want to add KeyListener
to JApplet
and it's not working.
Solution is to implement KeyEventDispatcher
instead of KeyListener
. Also I changed the size of your rectangle from 200 to 20 in order to be able to see the movements of the rectangle better:
package game;
import java.awt.Graphics;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import javax.swing.JApplet;
public class Gamer extends JApplet implements KeyEventDispatcher {
private int x = 50, y = 50;
@Override
public void init() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
}
@Override
public void paint(Graphics g) // will draw the background and the character
{
super.paint(g); // <- added to your code to clear the background
// before re-painting the new square
g.fillRect(x, y, 20, 20);
}
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
int keyCode = e.getKeyCode();
switch( keyCode )
{
case KeyEvent.VK_UP:
if( y>0 ) //when up key is pressed and the position of the player is not on the edge
{
y=y-19;
repaint();
}
break;
case KeyEvent.VK_DOWN:
if( y<171 ) //when down key is pressed and the position of the player is not on the edge
{
y=y+19;
repaint();
}
break;
case KeyEvent.VK_LEFT:
if( x>0 )
{
x=x-15;
repaint();
}
break;
case KeyEvent.VK_RIGHT:
if( x<285 )
{
x=x+15;
repaint();
}
break;
}
return false;
}
}
Hope this would be helpful.