• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1961
  • Last Modified:

JPanel.getGraphics() producing NullPointerException

Hi,

Anyone know how to get the graphics object from a JPanel.  The following code produces a NullPointerException on the line where I call:

System.out.println(rightPanel.getGraphics().toString());

All the unusual nonesense is just my attempt to get it to work.  the containing class is a JFrame, I am using 1.5.

Cheers,
Steve




private JPanel leftPanel, rightPanel, outPanel;

...


rightPanel = new JPanel(new BorderLayout()) {
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
   }
};


...


add(rightPanel, BorderLayout.EAST);

...

private void createGraphPanel() {

   rightPanel.add(new Canvas());
   rightPanel.setSize(200, 200);

   rightPanel.setVisible(true);

   Dimension d = rightPanel.getSize();

   System.out.println(d.toString());
   System.out.println(rightPanel.toString());
   System.out.println(rightPanel.getGraphics().toString());

   ....
0
steve_bagnall
Asked:
steve_bagnall
  • 4
  • 3
  • 2
2 Solutions
 
CEHJCommented:
The graphics context won't be available until the component has already been displayed
0
 
CEHJCommented:
Why, btw, do you want to get the Graphics?
0
 
objectsCommented:
> Anyone know how to get the graphics object from a JPanel.  

You should not access it, and should not need to.
The only time your application code should use the graphic context for a component is when it is passed to you by paint() method.
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
objectsCommented:
>    rightPanel.add(new Canvas());

You should also avoid mixing heavy and light weight components.
0
 
steve_bagnallAuthor Commented:
Hi,

Thanks for your responses.  I need a Graphics object to draw stuff on using Graphics2D?  Am I using the wrong container?

Cheers,
Steve
0
 
CEHJCommented:
>>Am I using the wrong container?

No, you can cast the Graphics to Graphics2D, but you must do that in paint or paintComponent as that's really the only time it's valid to use it anyway
0
 
steve_bagnallAuthor Commented:
OK thanks guys I see now I'm doing this the wrong way.
0
 
CEHJCommented:
:-)
0
 
objectsCommented:
(:
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

  • 4
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now