Медленная функция repaint() - Java

Узнай цену своей работы

Формулировка задачи:

Здравствуйте! Я пытаюсь написать арканоид по урокам из youtube. При запуске компилятором приложения картинка обновляется очень медленно, так что платформа, отбивающая мячик, перемещается на любое расстояние за 2 минуты, а не плавно. Еще возникает ошибка Exception in thread. Как можно решить проблему?
Листинг программы
  1. //Main.java
  2. package com.simplegame.arcanoid;
  3. import java.awt.*;
  4. import javax.swing.JFrame;
  5. /**
  6. * Created by Admin on 26.08.2017.
  7. */
  8. public class Main {
  9. public static void main(String[] args) {
  10. JFrame obj = new JFrame();
  11. game_mechanics mech = new game_mechanics();
  12. obj.setBounds(10, 10, 710, 630);
  13. obj.setTitle("Welcome to arcanoid!");
  14. obj.setVisible(true);
  15. obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  16. obj.add(mech);
  17. }
  18. }
  19. //BrickGenerator
  20. package com.simplegame.arcanoid;
  21. import javax.swing.*;
  22. import java.awt.*;
  23. /**
  24. * Created by Admin on 26.08.2017.
  25. */
  26. public class BrickGenerator {
  27. public int map[][];
  28. public int brickWidth;
  29. public int brickHeight;
  30. public BrickGenerator(int row, int col){
  31. map = new int[row][col];
  32. for(int i = 0; i < map.length; i++){
  33. for(int j = 0; j<map[0].length; j++){
  34. map[i][j] = 1;
  35. }
  36. }
  37. brickWidth = 540/col;
  38. brickHeight = 150/row;
  39. }
  40. public void draw(Graphics2D g ){
  41. for(int i = 0; i < map.length; i++){
  42. for(int j = 0; j<map[0].length; j++){
  43. if( map[i][j] > 0) {
  44. g.setColor(Color.WHITE);
  45. g.fillRect(j * brickWidth + 80, i* brickHeight + 50, brickWidth, brickHeight);
  46. }
  47. }
  48. }
  49. }
  50. }
  51.  
  52. //game_mechanics.java
  53.  
  54. package com.simplegame.arcanoid;
  55. import javax.swing.*;
  56. import java.awt.*;
  57. import java.awt.event.ActionEvent;
  58. import java.awt.event.ActionListener;
  59. import java.awt.event.KeyEvent;
  60. import java.awt.event.KeyListener;
  61.  
  62. public class game_mechanics extends JPanel implements KeyListener, ActionListener {
  63. private boolean play = false;
  64. private int score = 0;
  65. private int totalBricks = 21;
  66. private Timer time;
  67. private int delay = 8;
  68. private int playerX = 310;
  69. private int ballposX = 120;
  70. private int ballposY = 350;
  71. private int ballXdir = -1;
  72. private int ballYdir = -2;
  73. private BrickGenerator map;
  74. public game_mechanics(){
  75. BrickGenerator map = new BrickGenerator(3, 7);
  76. addKeyListener(this);
  77. setFocusable(true);
  78. setFocusTraversalKeysEnabled(false);
  79. Timer timer = new Timer(delay, this);
  80. timer.start();
  81. }
  82. public void paint(Graphics g) {
  83. // background
  84. g.setColor(Color.black);
  85. g.fillRect(1, 1, 692, 592);
  86. //drawing map
  87. map.draw((Graphics2D) g);
  88. //borders
  89. g.setColor(Color.yellow);
  90. g.fillRect(0, 0, 3, 592);
  91. g.fillRect(0, 0, 692, 3);
  92. g.fillRect(691, 0, 3, 592);
  93. //the paddle
  94. g.setColor(Color.green);
  95. g.fillRect(playerX, 550 , 100, 8);
  96. //the ball
  97. g.setColor(Color.yellow);
  98. g.fillOval(ballposX , ballposY , 20, 20);
  99. g.dispose();
  100. }
  101. @Override
  102. public void actionPerformed(ActionEvent e) {
  103. Timer timer = new Timer(delay, this);
  104. timer.start();
  105. if(play) {
  106. if(new Rectangle(ballposX, ballposY, 20, 20).intersects(new Rectangle(playerX, 550, 100, 8))){
  107. ballYdir = -ballYdir;
  108. }
  109. ballposX += ballXdir;
  110. ballposY += ballYdir;
  111. if(ballposX < 0) {
  112. ballXdir = -ballXdir;
  113. }
  114. if(ballposY < 0) {
  115. ballYdir = -ballYdir;
  116. }
  117. if(ballposX > 670) {
  118. ballXdir = -ballXdir;
  119. }
  120. }
  121. repaint();
  122. }
  123. @Override
  124. public void keyTyped(KeyEvent e) { }
  125. @Override
  126. public void keyPressed(KeyEvent e) {
  127. if(e.getKeyCode() == KeyEvent.VK_RIGHT){
  128. if(playerX >=600) {
  129. playerX = 600;
  130. } else{
  131. moveRight();
  132. }
  133. }
  134. if(e.getKeyCode() == KeyEvent.VK_LEFT){
  135. if(playerX < 10) {
  136. playerX = 10;
  137. } else{
  138. moveLeft();
  139. }
  140. }
  141. }
  142. public void moveRight() {
  143. play = true;
  144. playerX += 20;
  145. }
  146. public void moveLeft() {
  147. play = true;
  148. playerX -= 20;
  149. }
  150. @Override
  151. public void keyReleased(KeyEvent e) { }
  152. }

Решение задачи: «Медленная функция repaint()»

textual
Листинг программы
  1. import java.awt.*;
  2. import java.util.Random;
  3.  
  4. /**
  5.  * Created by Admin on 26.08.2017.
  6.  */
  7. public class BrickGenerator {
  8.     public int map[][];
  9.     public int brickWidth;
  10.     public int brickHeight;
  11.     private static Random rnd = new Random();
  12.  
  13.  
  14.     public BrickGenerator(int row, int col) {
  15.         map = new int[row][col];
  16.         for (int i = 0; i < map.length; i++) {
  17.             for (int j = 0; j < map[0].length; j++) {
  18.                 map[i][j] = (i+j+1)%2;
  19.             }
  20.         }
  21.         brickWidth = 540 / col;
  22.         brickHeight = 150 / row;
  23.     }
  24.  
  25.     public void draw(Graphics2D g) {
  26.         for (int i = 0; i < map.length; i++) {
  27.             for (int j = 0; j < map[0].length; j++) {
  28.                 if (map[i][j] > 0) {
  29.                     g.setColor(Color.WHITE);
  30.                     g.fillRect(j * brickWidth + 80, i * brickHeight + 50, brickWidth, brickHeight);
  31.  
  32.                 }
  33.             }
  34.         }
  35.     }
  36. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

13   голосов , оценка 3.923 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут