JComponent大小问题

Jac*_*k H 2 java swing graphics2d paintcomponent

我有一个JComponent子类,我用来在屏幕上绘制形状.在构造函数中,我试图设置ballXballY一半的XY大小的值JComponent,我想我做错了.我现在已经看了很多,但找不到补救措施.代码如下.请记住,这是我第一次真正的Swing/Graphics2D冒险.

public class PongCanvas extends JComponent {
//Vars to hold XY values and Dimension values.

    private int batXDim, batYDim;
    private int b1X, b1Y;
    private int b2X, b2Y;
    private int ballRad, ballX, ballY;

    public PongCanvas() {//Instantiate vars.
        batXDim = 20;
        batYDim = 100;

        b1X = 0;
        b1Y = 0;

        b2X = 0;
        b2Y = 0;

        ballRad = 20;
        ballX = getWidth() / 2;
        ballY = getHeight() / 2;
    }

    public void paint(Graphics g) {//Main paint Method.
        //Cast Graphics to Graphics2D.
        Graphics2D g2 = (Graphics2D) g;
        //Enable antialiasing.
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        //Draw background.
        g2.setPaint(Color.black);
        g2.fillRect(0, 0, getWidth(), getHeight());
        //Draw ball.
        g2.setPaint(Color.white);
        g2.fillOval(ballX, ballY, ballRad, ballRad);
        //Draw bat 1.
        g2.fillRect(b1X, b1Y, batXDim, batYDim);
        //Draw bat 2.
        g2.fillRect(b2X, b2Y, batXDim, batYDim);
    }
}
Run Code Online (Sandbox Code Playgroud)

tra*_*god 5

getPreferredSize()在你的覆盖中JComponent返回你的首选尺寸,并从它的宽度和高度的一半开始Dimension.为了同样的目的,这个KineticModel调用setPreferredSize()DisplayPanel.

附录:通过解释,当前的做法,因为从结果失败getWidth(),并getHeight()无效的,直到 validate()被称为封闭的容器上,通常作为的结果pack().