【发布时间】:2014-12-12 09:41:27
【问题描述】:
我设计了一个基本的乒乓球游戏,可以在 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 方法。我该如何解决这个问题?
【问题讨论】:
-
您在问“为什么我的代码不能正确运行”,但发布的是不可编译和不可运行的代码 sn-ps。为了获得更好的帮助,请考虑创建并发布一个minimal example program,这是一个尽可能最小的小程序,它可以为我们编译和运行,不需要图像,它可以向我们展示您的问题。这个程序应该非常简单,但同样应该演示问题。请查看链接。
标签: java windows macos swing paint