2011-11-05 83 views
2

我有一個JComponent子類,用於在屏幕上繪製形狀。在構造函數中,我試圖將ballXballY設置爲JComponentXY大小值的一半,並且我認爲我做錯了。我現在查了很多,並找不到補救辦法。代碼如下。請記住,這是我第一次真正的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); 
    } 
} 
+3

「Swing程序應該重寫'的paintComponent()'而不是'覆蓋塗料()'。」 - [繪畫在AWT和Swing:Paint Methods](http://java.sun.com/products/jfc/tsc/articles/painting/index.html#callbacks)。 – trashgod

回答

5

覆蓋getPreferredSize()JComponent來回報您的首選大小,並與Dimension的寬度和高度的一半開始。爲此,KineticModelDisplayPanel中調用setPreferredSize()

附錄:通過解釋,當前的做法,因爲從getWidth()getHeight()結果無效直到validate()被稱爲封閉的容器上,通常爲pack()結果失敗。

+0

對不起,我不確定我完全理解你的意思。 –

+0

通過覆蓋「paintComponent()」和「getPreferredSize()'這兩個方法更新您的示例。註解'@ Override'將被證明是有幫助的。 – trashgod

+0

好的,謝謝。一旦我的開發機器啓動並再次運行,我將進行更改(不斷收到內核恐慌)。 –

2

我同意trashgod的回答。 (+1)

移動ballX和BALLY在paintComponent(g)這樣

if (ballX==0 && ballY==0) { 
    ballX = getWidth()/2; 
    ballY = getHeight()/2; 
} 
+0

+1用於提示[前哨值](http://en.wikipedia.org/wiki/Sentinel_value)。當然,'(0,0)'然後成爲一種蟲洞的入口!我經常使用'Point p;'並稍後檢查'if(p == null)'來初始化起點。 – trashgod