[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1942
  • 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

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