JComponent大小问题

时间:2011-11-05 01:41:10

标签: java swing graphics2d paintcomponent

我有一个JComponent子类,用于在屏幕上绘制形状。在构造函数中,我尝试将ballXballY设置为JComponent X Y 大小值的一半,我想我做错了。我现在已经看了很多,但找不到补救措施。代码如下。请记住,这是我第一次真正的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);
    }
}

2 个答案:

答案 0 :(得分:5)

覆盖JComponent中的getPreferredSize()以返回您的首选尺寸,并从Dimension的宽度和高度的一半开始。同样,此KineticModel会在DisplayPanel中调用setPreferredSize()

附录:作为解释,您当前的方法失败,因为getWidth()getHeight()的结果无效,直到validate()被调用为止容器,通常是pack()的结果。

答案 1 :(得分:2)

我同意trashgod的回答。 (1)

将ballX和ballY移动到paintComponent(g)这样的

if (ballX==0 && ballY==0) {
    ballX = getWidth()/2;
    ballY = getHeight()/2;
}