0

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?

TheRealJimShady
  • 3,815
  • 4
  • 21
  • 40
  • Why do you need a global graphics object? Why can't you call `drawGridLines` from inside `paintComponent` and pass the `Graphics` as a parameter? – khelwood Oct 28 '14 at 11:51
  • that's what I've got at the moment - but is this a good solution if I'm going to be calling drawGridlines() from another class? – TheRealJimShady Oct 28 '14 at 11:52
  • It's better to pass the `Graphics` object to your helper functions than to try and store a `Graphics` object that might get disposed and no longer be usable. – khelwood Oct 28 '14 at 11:53
  • ...How would I pass in the graphics object externally? – TheRealJimShady Oct 28 '14 at 11:55

2 Answers2

5

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.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • +1 for factoring; the corresponding approach in [tag:jfreechart] may be seen among the various `drawXxx()` methods in the implementations of [`AbstractRenderer`](http://www.jfree.org/jfreechart/api/javadoc/org/jfree/chart/renderer/AbstractRenderer.html). – trashgod Oct 28 '14 at 12:24
5

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.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045