我有一個JComponent
子類,用於在屏幕上繪製形狀。在構造函數中,我試圖將ballX
和ballY
設置爲JComponent
的X和Y大小值的一半,並且我認爲我做錯了。我現在查了很多,並找不到補救辦法。代碼如下。請記住,這是我第一次真正的Swing/Graphics2D風險投資。JComponent size issue
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()'而不是'覆蓋塗料()'。」 - [繪畫在AWT和Swing:Paint Methods](http://java.sun.com/products/jfc/tsc/articles/painting/index.html#callbacks)。 – trashgod