我有一个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);
    }
}

最佳答案

getPreferredSize()中覆盖JComponent以返回您的首选大小,并以该Dimension的宽度和高度的一半开始。出于同一目的,此KineticModel调用setPreferredSize()中的DisplayPanel

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

关于java - JComponent大小问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8017561/

10-09 01:58