Java - 使用paintComponent作为图形,从内部调用函数?

时间:2011-07-30 16:23:11

标签: java swing graphics jpanel paintcomponent

我对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 个答案:

答案 0 :(得分:4)

从面板对象上的repaint方法调用startPanelView。您不应该对paint方法之外的图形对象进行操作,也不应该保留对图形对象的引用,以便在paint方法之外使用。

答案 1 :(得分:4)

其他人是正确的,你不能将Graphics对象保留为成员变量,但如果问题是你的paintComponent方法过长,你仍然可以通过{{1} Swing将您作为其他方法的参数:

Graphics

答案 2 :(得分:2)

  

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

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

答案 3 :(得分:1)

Swing中Painting/Custom Painting/2D Graphics的基本JComponentImage/ImageIcon的基本JLabel2D Graphics

不要从CustomPaintinghere调用其他视频或类别,一些有价值的示例是here或{{3}},请在此论坛上搜索有关Custom Painting2D Graphics

的优秀建议