小编Goo*_*ly_的帖子

JFrame getHeight()和getWidth()返回0

我正在做一个简单的乒乓球比赛; 并且部分碰撞力学需要获得画布的宽度和高度以重定向球.然而,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)

java swing paint jpanel thread-sleep

5
推荐指数
1
解决办法
6195
查看次数

标签 统计

java ×1

jpanel ×1

paint ×1

swing ×1

thread-sleep ×1