2

我对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 函数对我来说变得又长又复杂,所以我想以任何可能的方式分解它。

4

4 回答 4

4

repaintstartPanelView面板对象上的方法调用。您不应该在paint方法之外对图形对象进行操作,也不应该维护对图形对象的引用以在paint方法之外使用。

于 2011-07-30T16:30:22.143 回答
4

其他人是正确的,您不能将Graphics对象保留为成员变量,但如果问题是您的paintComponent方法变得太长,您仍然可以将GraphicsSwing 给您作为参数传递给其他方法:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawRect(350, 20, 400, 300);
    doSomeStuff(g);
    if (flag1) {
        doMoreStuff(g);
    } else {
        doDifferentStuff(g);
    }
}
于 2011-07-30T17:00:55.873 回答
2

我想访问 Graphics 对象以根据我的程序流程从其他函数中绘制内容。我正在考虑以下几点:

不,您不应该在标准的 Swing 应用程序中这样做,因为所获得的 Graphics 对象将不会持续存在,并且只要 JVM 或操作系统决定需要重新绘制,您的绘图就会消失。考虑创建列表或其他要绘制的对象集合(例如从实现 的类Shape)并在 paintComponent 方法中迭代这些集合。另一种技术是在 BufferedImage 上绘图,然后在您的 paintComponent 方法中显示它。

于 2011-07-30T16:32:00.423 回答
1

Swing 或Image/ImageIcon的基本JComponentJLabelPainting/Custom Painting/2D Graphics

不要从2D GraphicsCustomPainting调用另一个 viod(s) 或 class(es) ,一些有价值的例子在这里这里,在这个论坛上搜索关于Custom Painting和的优秀建议2D Graphics

于 2011-07-30T16:39:01.163 回答