2

I have a JComponent subclass that I am using to draw shapes onto my screen. In the constructor, I am trying to set ballX and ballY to half of the X and Y size values of the JComponent, and I think I am doing it wrong. I have looked this up a lot now, and cannot find a remedy. The code is as follows. Please bear in mind that this is my first real Swing/Graphics2D venture.

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);
    }
}
4

2 回答 2

5

覆盖getPreferredSize()JComponent以返回您的首选尺寸,并从该Dimension. 出于同样的目的,这KineticModel调用setPreferredSize()了 in DisplayPanel

附录:作为解释,您当前的方法失败,因为在封闭容器上调用getWidth()和之前 的结果getHeight()无效的,通常是.validate()pack()

于 2011-11-05T02:28:09.033 回答
2

我同意trashgod的回答。(+1)

paintComponent(g)像这样移动ballX和ballY

if (ballX==0 && ballY==0) {
    ballX = getWidth()/2;
    ballY = getHeight()/2;
}
于 2011-11-05T07:22:28.980 回答