gpt4 book ai didi

java - JComponent 大小问题

转载 作者:行者123 更新时间:2023-12-03 21:40:53 29 4
gpt4 key购买 nike

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

最佳答案

覆盖 getPreferredSize()在您的 JComponent 中返回您的首选大小,并从该 Dimension 的宽度和高度的一半开始。为了同样的目的,这 KineticModelDisplayPanel 中调用 setPreferredSize() .

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

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

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com