2013-04-30 36 views
0

Graph對象添加到JFrame。該對象繪製軸後跟一個圖形圖。直接調用paint()時繪圖元素,但添加到內容窗格時繪製的元素

this.getContentPane().add(new Graph()); 

軸和功能都抽籤:當物體的paint()被隱含通過JFrame使用調用。然而,當paint()方法顯式調用,通過:

Graph g = new Graph(); 
g.paint(this.getContentPane().getGraphics()); 

軸不畫,但是功能一樣。爲JFrame完整的構造函數如下:

public GraphFrame() { 
    super(""); 
    setSize(800, 800); 
    setVisible(true); 
    //One of the above blocks is called here 
} 

功能paint在對象Graph如下:

public void paint(Graphics w) { 
    w.setColor(Color.WHITE); 
    w.fillRect(0, 0, 800, 800); //Clears the screen 
    w.setColor(Color.BLACK); 
    w.drawLine(100, 0, 100, 800); 
    w.drawLine(0, 700, 800, 700); //(Should) Draw the axes 
    for(int i = 1; i < 650; i++) { 
     //Draws the function 
     //This is just a repeated drawLine call. 
    } 
} 

爲什麼軸畫時,當部件油漆隱式調用,而不是畫時顯式調用?請記住該函數將繪製(for循環中的塊),而for循環之前的軸則不會。

+0

你爲什麼要叫'漆(...)'直接?這是最不尋常的做法,並且違背了圖形教程中的大多數建議,並且根據你想要做的事情沒什麼意義。您是否瀏覽過Swing圖形教程?如果不是的話,你應該儘可能多地提供給你。 – 2013-04-30 18:42:45

回答

2

不要直接在組件上調用paint。此外,對於Swing中的自定義繪畫,請使用paintComponent而不是paint,並記得撥打super.paintComponent(g)。另外getGraphics返回一個暫時的Graphics參考,因此不應該用於自定義繪畫。相比之下,paint(和paintComponent)中的Graphics參考始終正確初始化,並將按預期顯示圖形輸出。