how to move a rectangle with arrow keys,
for some reason this only works for the right arrow key, and i commented out the code for the left arrow key. how do you edit the paint method in the keyhandler method below? or otherwise, how do you reference the keyhandler event/ keypressed in the paint method up top?
import java.awt.Container;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
public class BreakOut extends javax.swing.JFrame
{
// constants used to define the game field and bounds
public static final int GAME_WINDOW_HEIGHT = 512;
public static final int GAME_WINDOW_WIDTH = 512;
public static final int GAME_HEIGHT = 440;
public static final int GAME_WIDTH = 440;
private static final int BLOCK_WIDTH=90;
private static final int BLOCK_HEIGHT=50;
private Paddle p;
private KeyHandler kh;
public BreakOut()
{
p=new Paddle(100,Color.RED);
Container container=getContentPane();
container.setBackground(Color.WHITE);
initComponents();
}
public void paint(Graphics g)
{
super.paint(g);
g.setColor(p.getPadColor());
if(p.isVisible())
{
g.fillRect(p.getXLocation(),100,70,20);
}
if(!p.isVisible())
{
g.clearRect(p.getXLocation()-10,100,70,20);
p.setVisibility(true);
repaint();
}
}
public void initComponents()
{
setDefaultCloseOperation(javax.swing.WindowConstan ts.EXIT_ON_CLOSE);
setSize(GAME_WINDOW_WIDTH, GAME_WINDOW_HEIGHT);
setTitle("BreakOut");
}
public static void main(String[] args)
{
BreakOut game = new BreakOut();
game.setVisible(true);
}
public class KeyHandler extends KeyAdapter
{
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyCode()==KeyEvent.VK_RIGHT)
{
p.setVisibility(false);
p.setXLocation(p.getXLocation()+10);
repaint();
}
if(ke.getKeyCode()==KeyEvent.VK_LEFT)
{
//p.setVisibility(false);
//p.setXLocation(p.getXLocation()-10);
//repaint();
}
}
}
import java.awt.Color;
public class Paddle
{
private int xlocation;
private Color padColor;
private boolean isVisible;
public Paddle(int xlocation, Color padColor)
{
this.xlocation=xlocation;
this.padColor=padColor;
this.isVisible=true;
}
public int getXLocation()
{
return this.xlocation;
}
public Color getPadColor()
{
return this.padColor;
}
public void setXLocation(int xlocation)
{
this.xlocation=xlocation;
}
public void setPadColor(Color padColor)
{
this.padColor=padColor;
}
public boolean isVisible()
{
return this.isVisible;
}
public void setVisibility(boolean isVisible)
{
this.isVisible=isVisible;
}
}
Re: how to move a rectangle with arrow keys,