我正在做一个简单的乒乓球比赛; 并且部分碰撞力学需要获得画布的宽度和高度以重定向球.然而,getWidth()和getHeight()由于某些原因返回0.这是主要的代码块.
package pong;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JPanel {
static int gameSpeed = 10;
Ball ball = new Ball(this);
private void move() {
ball.move();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
ball.paint(g2d);
}
public static void main(String args[]) throws InterruptedException {
JFrame frame = new JFrame("Pong");
Main game = new Main();
frame.add(game);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.move();
game.repaint();
Thread.sleep(gameSpeed);
}
} …Run Code Online (Sandbox Code Playgroud)