The problem with the above code was that the flag value inside keyPressed(KeyEvent e) method is always false.
As
@OriginalGriff has mentioned that the flag is always set to false;
package animation;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class MovingImage extends JPanel implements KeyListener{
static class Shooter{
int startx,starty;
int width;
int height;
Shooter(int x,int y,int w,int h){
startx=x;
starty=y;
width=w;
height=h;
}
}
Graphics2D g;
BufferedImage img;
Shooter shoot;
MovingImage(){
setSize(700,700);
img=new BufferedImage(700,700,BufferedImage.TYPE_4BYTE_ABGR);
g=img.createGraphics();
shoot=new Shooter(300,300,50,50);
g.fillRect(shoot.startx, shoot.starty, shoot.width, shoot.height);
repaint();
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_RIGHT){
Color back=this.getBackground();
Color front=g.getColor();
g.setColor(back);
g.fillRect(shoot.startx, shoot.starty, shoot.width, shoot.height);
g.setColor(front);
shoot.startx++;
g.fillRect(shoot.startx, shoot.starty,shoot.width , shoot.height);
g.drawImage(img, 0,0, this);
repaint();
}
if(e.getKeyCode()==KeyEvent.VK_LEFT){
Color back=this.getBackground();
Color front=g.getColor();
g.setColor(back);
g.fillRect(shoot.startx, shoot.starty, shoot.width, shoot.height);
g.setColor(front);
shoot.startx--;
g.fillRect(shoot.startx, shoot.starty,shoot.width , shoot.height);
g.drawImage(img, 0,0, this);
repaint();
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void paint(Graphics g){
g.drawImage(img,0,0, this);
}
public static void main(String[] args) {
JFrame frame =new JFrame();
frame.setSize(700,700);
MovingImage moving_img=new MovingImage();
frame.add(moving_img);
frame.addKeyListener(moving_img);
frame.setVisible(true);
}
}