JComponent大小问题 [英] JComponent size issue
问题描述
我有一个JComponent
子类,用于在屏幕上绘制形状.在构造函数中,我试图将ballX
和ballY
设置为JComponent
的 X 和 Y 大小值的一半,我认为做错了.我现在已经对此进行了很多查找,并且找不到补救措施.代码如下.请记住,这是我第一次真正的Swing/Graphics2D创业.
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);
}
}
推荐答案
覆盖 KineticModel
在
Override getPreferredSize()
in your JComponent
to return your preferred size, and start with half the width and height of that Dimension
. To the same end, this KineticModel
invokes setPreferredSize()
in DisplayPanel
.
附录:作为解释,您的当前方法失败了,因为getWidth()
和getHeight()
的结果为无效,直到在封闭容器上调用validate()
为止,通常是作为结果的 pack()
.
Addendum: By way of explanation, your current approach fails because the results from getWidth()
and getHeight()
are invalid until validate()
has been called on the enclosing container, typically as the result of pack()
.
这篇关于JComponent大小问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!