Advertisement
Guest User

Untitled

a guest
Dec 11th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. import java.awt.Graphics;
  2. import java.awt.Graphics2D;
  3. import javax.swing.JComponent;
  4. import java.awt.event.KeyEvent;
  5. import java.awt.event.KeyListener;
  6. import java.awt.event.ActionEvent;
  7. /**
  8. *
  9. This component draws two car shapes.
  10. */
  11. public class CarComponent extends JComponent implements KeyListener
  12. {
  13.  
  14. private static final int BOX_X = 100;
  15. private static final int BOX_Y = 100;
  16. private static final int BOX_WIDTH = 60;
  17. private static final int BOX_HEIGHT = 30;
  18. private boolean upPressed=false;
  19. private boolean downPressed=false;
  20. private boolean leftPressed=false;
  21. private boolean rightPressed=false;
  22.  
  23. Car car1;
  24.  
  25.  
  26.  
  27. public CarComponent()
  28. {
  29. setFocusable(true);
  30. addKeyListener(this);
  31. car1 = new Car(0,0);
  32.  
  33.  
  34.  
  35. }
  36.  
  37.  
  38. public void paintComponent(Graphics g)
  39. {
  40. Graphics2D g2 = (Graphics2D) g;
  41.  
  42. car1.draw(g2);
  43.  
  44.  
  45. }
  46.  
  47.  
  48.  
  49. public void move()
  50. {
  51.  
  52. java.awt.Point p = car1.getLocation();
  53. int x=p.x;
  54. int y=p.y;
  55. if (rightPressed){
  56. if(x<getWidth())
  57. x+=1;
  58. else
  59. x=0;
  60. }
  61. if (leftPressed){
  62. if(x<getWidth())
  63. x-=1;
  64. else
  65. x=0;
  66. }
  67. if (upPressed){
  68. if(y<getHeight())
  69. y+=1;
  70. else
  71. y=0;
  72. }
  73. if (downPressed){
  74. if(y<getHeight())
  75. y-=1;
  76. else
  77. y=0;
  78. }
  79.  
  80. car1.setLocation(x,y);
  81.  
  82. repaint();
  83.  
  84. }
  85. public void keyType(KeyEvent e){}
  86. public void keyPressed(KeyEvent e){
  87. if (e.getKeyCode()==KeyEvent.VK_UP){
  88. upPressed=true;
  89. }
  90. else if(e.getKeyCode()==KeyEvent.VK_DOWN){
  91. downPressed=true;
  92. }
  93. else if (e.getKeyCode()==KeyEvent.VK_LEFT){
  94. leftPressed=true;
  95. }
  96. else if (e.getKeyCode()==KeyEvent.VK_RIGHT){
  97. rightPressed=true;
  98. }
  99.  
  100.  
  101. }
  102. public void keyReleased(KeyEvent e){
  103. if (e.getKeyCode()==KeyEvent.VK_UP){
  104. upPressed=false;
  105. }
  106. else if(e.getKeyCode()==KeyEvent.VK_DOWN){
  107. downPressed=false;
  108. }
  109. else if (e.getKeyCode()==KeyEvent.VK_LEFT){
  110. leftPressed=false;
  111. }
  112. else if (e.getKeyCode()==KeyEvent.VK_RIGHT){
  113. rightPressed=false;
  114. }
  115.  
  116.  
  117. }
  118.  
  119. @Override
  120. public void keyTyped(KeyEvent ke) {
  121. throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  122. }
  123.  
  124. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement