drawing to a JPanel without inheritance

Posted by g.rocket on Stack Overflow See other posts from Stack Overflow or by g.rocket
Published on 2012-03-27T17:26:06Z Indexed on 2012/03/27 17:29 UTC
Read the original article Hit count: 282

Filed under:
|

Right now I'm working on a program that throws up a bunch of separate (generated at runtime) images, each in their own window. To do this i've tried this approach:

public void display(){
    JFrame window = new JFrame("NetPart");
    JPanel canvas = new JPanel();
    window.getContentPane().add(canvas);
    Graphics g = canvas.getGraphics();
    Dimension d = getSize();
    System.out.println(d);
    draw(g,new Point(d.minX*50,d.maxY*50), 50);
    window.setSize(d.size(50));
    window.setResizable(false);
    window.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    window.setVisible(true);
}

public void draw(Graphics g, Point startLoc, int scale){
    // generate and draw the image
}

public Dimension getSize(){
    //returns my own dimensions class
}

However, this throws a NullPointerException in draw, claiming that the graphics is null. is there any way to externally draw to a JPanel from outside it (not inherit from JPanel and override PaintComponent)? Any help would be appreciated.

© Stack Overflow or respective owner

Related posts about java

Related posts about jpanel