我對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功能越來越愚蠢長期而複雜的我,所以我想打破它以任何方式成爲可能。
當然,我會嘗試。但是,它是如何設計的?出於好奇。 – JDS
每個Swing組件都有自己的圖形對象。你能想象不得不跟蹤每個組件的圖形對象,並按照正確的順序在適當的時間單獨操作它們嗎? –