Java: Create global graphics object

☆樱花仙子☆ 提交于 2019-12-20 07:07:02

问题


I've extended the JPanel class to draw a graph. The problem that I've got is that I need a global graphics object in order to call it in multiple methods... As an example, here's what I'm trying to do:

public class Graph extends JPanel {
  private Graphics2D g2d;

  public void paintComponent(Graphics g){
    g2d = (Graphics2D)g;
  }

  public void drawGridLines(int hor, int vert){
    g2d.someLogicToDrawMyGridLines(someparams);
  }
}

This returns a null pointer exception - so my question is: how do I create a global graphics object? What's the best practice in this situation?


回答1:


My suggestion would be this:

public class Graph extends JPanel {
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g2d = (Graphics2D) g;
        drawGridLines(g2d, ......);
    }

    private void drawGridLines(Graphics2D g2d, int hor, int vert){
        g2d.someLogicToDrawMyGridLines(someparams);
    }
}

i.e. keep all the uses of your graphics context inside the paintComponent call.




回答2:


How would I pass in the graphics object externally?

Don't. The graphics context is only valid during the invocation of paintComponent(). Instead, use the MVC pattern, discussed here, to update a model that notifies any listening view to render itself. JFreeChart is a complete example.



来源:https://stackoverflow.com/questions/26607614/java-create-global-graphics-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!