JFrame getHeight()和getWidth()返回0

Goo*_*ly_ 5 java swing paint jpanel thread-sleep

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

这是实际的Ball类,它处理运动条件.

package pong;

import javax.swing.*;
import java.awt.*;

public class Ball extends JPanel {

    int x = 1;
    int y = 1;
    int dx = 1;
    int dy = 1;
    private Main game;

    public Ball(Main game) {
        this.game = game;
    }

    void move() {
        System.out.println(getWidth() + getHeight());

        if (x + dx < 0) {
            dx = 1;
        }
        if (y + dy < 0) {
            dy = 1;
        }
        if (x + dx > (getWidth() - 30)) {
            dx = -1;
        }
        if (y + dy > (getHeight() - 30)) {
            dy = -1;
        }
        x = x + dx;
        y = y + dy;
    }

    public void paint(Graphics2D g) {
        g.fillOval(x, y, 30, 30);
    }
} 
Run Code Online (Sandbox Code Playgroud)

编辑:问题解决了,我只是没有告诉getWidth()和getHeight()引用什么.显然,如果我不告诉他们要得到什么,他们将返回null.DERP.简单的解决方法是将它们更改为game.getWidth()和game.getHeight().谢谢你的帮助!您的所有输入也有助于其他领域.:)

mKo*_*bel 7

  1. Graphics/ Java2D默认情况下,从来没有returs合理的Dimension,结果是零Dimension,你要重写getPreferredSizeJPanel,然后getWidth/Height将返回正确的坐标为JPanels'大小.

  2. 然后使用JFrame.pack()而不是任何尺寸.

  3. 覆盖paintComponentSwing JComponents,而不是paint(),里面paintComponent第一次.代码行应该是super.paintComponent,否则绘制累积.

  4. 从来没有使用Thread.sleep(int)Swing,也不是风俗画或动画在Java7和Swing,使用Swing Timer的停止,而不是无休止的循环Thread.sleep(int).