• Post Reply Bookmark Topic Watch Topic
  • New Topic

getGraphics() return null  RSS feed

 
Mohamad Norouzi
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a problem with getGraphics()

I have a class as follow:
-------------------------------------------
public class sinx1 extends CFunction{
protected double f(double x){
return Math.sin(x*x*x)+Math.tan(x))/(Math.cos(x*x)-Math.sin(x));
}

public void draw(Canvas c){
Graphics g = (Graphics)c.getGraphics(); //***** POINT A
draw(g);
}
public sinx1(int mx,int my){
super();
maxx = mx;
maxy = my;
}
}
----------------
when I create a new instance of Canvas and pass it to method draw()
the c is not null but when I call its getGraphics() it returns null so g is null. I think getGraphics always returns null because when I used a JPanel and call its getGraphics and pass it to that method, it returns null again.


please help me how can I get a Graphic (or context of a component) and do something with it. I dont want to extend another component and use its paint() or update() methods.

thanks
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
getGraphics() returns null if you call it on a component which isn't shown on the screen; "unrealized" components don't have a Graphics object associated with them.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note, also, that if you draw on something this way, then as soon as the screen needs updating (other window obscures the app, window resized, etc) then you'll be left with an ugly blank area. It's only by overriding paint() that you enable Java to repaint the window as needed. Why not explain to us exactly what you're trying to achieve, and we can offer some advice on how to do it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!