In the below program I am just trying to move the box on the screen based on the key pressed.I have to clear the last position of the box and draw its new position .When flag is true I will clear the screen and when the flag is false I will draw it on the screen
but the flag value is false its not changing inside the keyPressed(KeyEvent e) method of Shoot class.
Remove the comment statement inside the paint(Graphics g) method of Shoot class and u will find the flag is always false.
Why is it so?
Thanks in advance ;)
import java.awt.Color;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import java.awt.event.KeyListener;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
public class Shoot extends JPanel implements KeyListener,WindowListener{
int x=300,y=300;
int width=50,height=50;
boolean flag=false;
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT){
flag=true;
repaint();
x--;
flag=false;
repaint();
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT){
flag=true;
repaint();
x++;
flag=false;
repaint();
}
}
@Override
public void paint(Graphics g){
if(flag){
g.setColor(getBackground());
g.drawRect(x, y, width, height);
g.setColor(Color.black);
}
else
g.drawRect(x, y, width, height);
}
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
public static void main(String $[]){
JFrame frame =new JFrame();
frame.setSize(700,700);
Shoot shoot=new Shoot();
shoot.setSize(700,700);
frame.addKeyListener(shoot);
frame.addWindowListener(shoot);
frame.add(shoot);
frame.setVisible(true);
}
}
What I have tried:
@Override
public void paint(Graphics g){
System.out.println(flag);
if(flag){
g.setColor(getBackground());
g.drawRect(x, y, width, height);
g.setColor(Color.black);
}
else
g.drawRect(x, y, width, height);
}
The flag value is always coming false.