2011-07-30 27 views
2

我對paintComponent函數在我的JPanel中的工作方式感到困惑。理想情況下,我想訪問Graphics對象,根據我的程序流從其他函數中抽取東西。我正在考慮以下內容:Java - 使用paintComponent爲圖形,從內部調用函數?

private Graphics myG; 

public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    myG = g; //I want a graphics object that I can just draw with. 
      //Should I just initialize to myG = new Graphics(); or something? 
    //private Graphics myG = new Graphics(); does not seem to work   
    } 

//this is what's getting called, where I want to call other functions that 
//can use myG to draw graphics as I please 
public void startPanelView() {  

    myG.drawRect(350, 20, 400, 300); //doesn't work 

    otherFunctionForGraphics(); //which will also use myG. 
} 

我希望我在這裏說清楚。我只是希望能夠隨心所欲地使用Graphics類。目前,我只能在paintComponent()函數中執行諸如g.drawRect(...)之類的內容。這可以用於我的目的,但我想要更多的靈活性。

謝謝。

編輯 - 好吧,我明白我不應該嘗試引用外部的Graphics對象。但我應該如何去分離paintComponent函數的應用程序邏輯?眼下這個類看起來有點亂,因爲我有以下幾點:

public void paintComponent(Graphics g) { 

    if (flag1 == true) { 
     //do some graphics stuff, that I would prefer to be in another function 
    } 

    if (flag2 == true) { 
     //do some other graphics stuff, again, which I would prefer 
     //to be in another function 
    } 

    //... etc. More of these cases. 
} 

而且基本的paintComponent功能越來越愚蠢長期而複雜的我,所以我想打破它以任何方式成爲可能。

回答

4

從面板對象上的startPanelView方法調用repaint。您不應該對paint方法以外的圖形對象採取行動,也不應該保留對在paint方法之外使用的圖形對象的引用。

+0

當然,我會嘗試。但是,它是如何設計的?出於好奇。 – JDS

+1

每個Swing組件都有自己的圖形對象。你能想象不得不跟蹤每個組件的圖形對象,並按照正確的順序在適當的時間單獨操作它們嗎? –

2

我想訪問Graphics對象來根據我的程序流從其他函數中抽取東西。我正在考慮以下內容:

不,您不應該在標準Swing應用程序中這樣做,因爲所獲得的Graphics對象不會持久存在,並且只要JVM或操作系統決定重繪是必要的。考慮創建列表或其他要繪製的對象集合(例如實現Shape的類)並在paintComponent方法中迭代這些集合。另一種技巧是繪製BufferedImage,然後將其顯示在paintComponent方法中。

+0

用於提及備用方法的+1(使用BufferedImage)** DOES **允許海報在paintComponent()方法之外訪問單獨的Graphics對象。希望[自定義繪畫方法]中的「繪製圖像」示例(http://tips4java.wordpress.com/2009/05/08/custom-painting-approaches/)將擴展此方法。 – camickr

4

其他人是正確的,你不能保持Graphics對象作爲成員變量,但如果問題是,你的paintComponent方法越來越太長,則CA n仍然通過Graphics擺動讓你作爲其他方法的參數:

public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    g.drawRect(350, 20, 400, 300); 
    doSomeStuff(g); 
    if (flag1) { 
     doMoreStuff(g); 
    } else { 
     doDifferentStuff(g); 
    } 
} 
+0

很高興知道,謝謝 – JDS