Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import javax.swing.JComponent;
- import java.awt.event.KeyEvent;
- import java.awt.event.KeyListener;
- import java.awt.event.ActionEvent;
- /**
- *
- This component draws two car shapes.
- */
- public class CarComponent extends JComponent implements KeyListener
- {
- private static final int BOX_X = 100;
- private static final int BOX_Y = 100;
- private static final int BOX_WIDTH = 60;
- private static final int BOX_HEIGHT = 30;
- private boolean upPressed=false;
- private boolean downPressed=false;
- private boolean leftPressed=false;
- private boolean rightPressed=false;
- Car car1;
- public CarComponent()
- {
- setFocusable(true);
- addKeyListener(this);
- car1 = new Car(0,0);
- }
- public void paintComponent(Graphics g)
- {
- Graphics2D g2 = (Graphics2D) g;
- car1.draw(g2);
- }
- public void move()
- {
- java.awt.Point p = car1.getLocation();
- int x=p.x;
- int y=p.y;
- if (rightPressed){
- if(x<getWidth())
- x+=1;
- else
- x=0;
- }
- if (leftPressed){
- if(x<getWidth())
- x-=1;
- else
- x=0;
- }
- if (upPressed){
- if(y<getHeight())
- y+=1;
- else
- y=0;
- }
- if (downPressed){
- if(y<getHeight())
- y-=1;
- else
- y=0;
- }
- car1.setLocation(x,y);
- repaint();
- }
- public void keyType(KeyEvent e){}
- public void keyPressed(KeyEvent e){
- if (e.getKeyCode()==KeyEvent.VK_UP){
- upPressed=true;
- }
- else if(e.getKeyCode()==KeyEvent.VK_DOWN){
- downPressed=true;
- }
- else if (e.getKeyCode()==KeyEvent.VK_LEFT){
- leftPressed=true;
- }
- else if (e.getKeyCode()==KeyEvent.VK_RIGHT){
- rightPressed=true;
- }
- }
- public void keyReleased(KeyEvent e){
- if (e.getKeyCode()==KeyEvent.VK_UP){
- upPressed=false;
- }
- else if(e.getKeyCode()==KeyEvent.VK_DOWN){
- downPressed=false;
- }
- else if (e.getKeyCode()==KeyEvent.VK_LEFT){
- leftPressed=false;
- }
- else if (e.getKeyCode()==KeyEvent.VK_RIGHT){
- rightPressed=false;
- }
- }
- @Override
- public void keyTyped(KeyEvent ke) {
- throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement