【发布时间】:2011-11-05 01:41:09
【问题描述】:
我有一个JComponent 子类,用于在我的屏幕上绘制形状。在构造函数中,我试图将ballX 和ballY 设置为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);
}
}
【问题讨论】:
-
"Swing 程序应该覆盖
paintComponent(),而不是覆盖paint()。"—Painting in AWT and Swing: The Paint Methods。
标签: java swing graphics2d paintcomponent