Only 44 hours left in the trailboss' kickstarter!

New rewards and stretch goals. CLICK HERE!



Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Graphics Grumbling  RSS feed

 
simcel jones
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello and thank you for taking the time to read this
I am unsure why the following code does not display Hello
It compiles just fine but when it is run it comes up with a Null Pointer exception on the line
g.drawString("Hello",50,50);

import java.awt.*;
import javax.swing.*;
public class MyApp extends JFrame
{
JPanel p=new JPanel();

public MyApp()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
Graphics g=p.getGraphics();
g.drawString("Hello",50,50);
setContentPane(p);
}

public static void main(String args[])
{
MyApp f = new MyApp();
f.setSize(800,500);
f.show();
}
}

thanks for helping
simon
 
Jason Stortz
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simcel,
I think I may have at least a little here to get you going in the right direction. For starters, the .getGraphics() call is to be used on Components. JPanel extends from JComponent and not component so that isn't fetching up the graphics for you like you want. Now, I've reworked your code with a couple slight modifications, take a look at it and see if this helps any. I understand you're wanting to play with the graphics capabilities, otherwise you'd probably just use a JLabel or something like that. Anyways, here you go:

Now, you may want to clean it up some, get rid of stuff here and there, but it works and prints out Hello.
Hope this helps, best of luck!
Jason
[This message has been edited by Jason Stortz (edited January 13, 2001).]
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would seem that you have not added your Panel (or JPanel) to your Application's layout. You will need to do that in order to draw on it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!