4 Replies - 808 Views - Last Post: 01 January 2008 - 02:58 AM Rate Topic: -----

#1 jowharshamshiri  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 65
  • Joined: 24-December 07

how can i draw on an applet?

Posted 31 December 2007 - 03:49 PM

hi,
i am comfortable drawing on JFrame but that same code doesnt work on JApplet. i get a null pointer exception for the returned graphics object of getGraphics() method although the method is shared by both components. here is what i have.
import javax.swing.*;
public class myClass extends JApplet{
	public myClass(){this.getGraphics().fillRect(10, 10, 100, 100);}
	public static void main(String[] args) {new myClass();}
}



help me by correcting it please.

Is This A Good Question/Topic? 0
  • +

Replies To: how can i draw on an applet?

#2 dontKnowJava  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 221
  • Joined: 29-September 07

Re: how can i draw on an applet?

Posted 31 December 2007 - 03:54 PM

im not 100% on this, but i believe applets main method should be void init() instead of public static void main()
Was This Post Helpful? 0
  • +
  • -

#3 jowharshamshiri  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 65
  • Joined: 24-December 07

Re: how can i draw on an applet?

Posted 31 December 2007 - 04:10 PM

thats not where my problem is. i do compile and run the code. and it does produce an applet. what i get a null pointer exception for is the graphics object returned by getGraphics() method.
Was This Post Helpful? 0
  • +
  • -

#4 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5931
  • View blog
  • Posts: 12,854
  • Joined: 16-October 07

Re: how can i draw on an applet?

Posted 31 December 2007 - 09:27 PM

You're trying to draw something before your applet is even started. There is no Graphics context to be had at that point, thus the null object. The solution is to put your code in the paint method and use the Graphics object that's given to that method.
public class myClass extends JApplet {
	public myClass(){ }
	public void paint(Graphics g) {
		g.fillRect(10, 10, 100, 100);
	}
}



Hope this helps.
Was This Post Helpful? 1

#5 jowharshamshiri  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 65
  • Joined: 24-December 07

Re: how can i draw on an applet?

Posted 01 January 2008 - 02:58 AM

wow! i love you man! thats probably the 3rd time your saving me. keep up the good work. :^:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1