我对paintComponent
函数在我的JPanel
. 理想情况下,我希望能够访问 Graphics 对象以根据我的程序流程从其他函数中绘制内容。我正在考虑以下几点:
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 类。目前我只能做函数g.drawRect(...)
内部的事情paintComponent()
。这可能适用于我的目的,但我想要更多的灵活性。
谢谢。
编辑 - 好的,我知道我不应该尝试在外部引用 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 函数对我来说变得又长又复杂,所以我想以任何可能的方式分解它。