我设计了一款在Windows上完美运行的基本乒乓球游戏,但它可以在Mac OS X上编译和运行,但它不会绘制任何东西。
JFrame的代码:
import javax.swing.JFrame;
public class Interface extends JFrame {
/**
* Creates a reference to a new Interface object. Sets all the parameters of the window
*/
public Interface() {
setTitle("Pong");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(600, 250, 506, 500); //setBounds(x, y, width, height)
setResizable(false);
setVisible(true);
}
/**
* The main method that the program is run from.
* @param args Command line arguments that are ignored by this method
*/
public static void main(String[] args) {
Interface window = new Interface();
Display d = new Display();
window.getContentPane().add(d);
window.addKeyListener(d); //allows the user to do a certain function from the object "d", if a specified key is pressed
d.run();
}
JPanel的基本代码:
public void paint(Graphics g) {
//set the background
g.setColor(Color.BLACK);
g.fillRect(0, 0, 500, 500);
//draws the net
g.setColor(Color.WHITE);
int yCoord = 0;
for (int i = 0; i < 16; i ++) {
g.fillRect(248, yCoord, 4, 15);
yCoord += 30;
}
//draws the players paddles
player1.draw(g);
player2.draw(g);
//draws the ball
ball.draw(g);
//draws the player scores
g.setColor(Color.WHITE);
g.drawString(player1.getScore()+" "+player2.getScore(), 224, 10);
}
//Constructor
public Display() {
player1 = new Player(10, 10, 1);
player2 = new Player(480, 10, 2);
ball = new Ball();
}
@Override
public void run() {
boolean running = true;
long startloop;
long wait;
long elapsed = 0;
System.out.println("Game is running");
while (running) {
startloop = System.nanoTime(); //starts the timer
//if (elapsed >= 1) {
//checks to see if there is a winner and updates the location and drawing of the ball
int win = ball.update();
//checks to see if the ball has collided with anyone
if (ball.checkPlayerCollision(player1)) {
ball.collideWithPlayer(player1);
} else if (ball.checkPlayerCollision(player2)) {
ball.collideWithPlayer(player2);
}
if (win == 1) {
player1.scored();
ball.reset();
} else if (win == 2) {
player2.scored();
ball.reset();
}
repaint(); //redraws the entire panel
elapsed = 0;
//}
elapsed += (System.nanoTime() - startloop);
wait = targetTime - elapsed / 1000000;
if(wait < 0) {
wait = 5;
}
//makes the while loop pause
try {
Thread.sleep(wait);
} catch(Exception e) {
e.printStackTrace();
}
}
}
我尝试将print语句放在任何地方,一切正常,它只是不会访问paint方法。我该如何解决这个问题?
答案 0 :(得分:3)
您的代码:
public static void main(String[] args) {
Interface window = new Interface();
Display d = new Display();
window.getContentPane().add(d);
window.addKeyListener(d);
d.run(); // ***************** here ***************
}
您似乎正在调用Thread的run()
方法或runnable(您不会显示类标题,因此无法知道),这可以保证不会有后台线程制作。而是调用包含Runnable的Thread的start()
方法。
所以也许你会想要改变
d.run();
为:
new Thread(d).start();
但是,在将来,当问及为什么我的代码无法正常运行&#34;时,请考虑创建并发布minimal example program,一个小程序,尽可能小的,为我们编译和运行,无需图像,这向我们展示了您的问题。
暂且不说:
paint(...)
方法,而应覆盖其paintComponent(...)
方法。