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

[Java] Getting stuff drawn on a swing component  RSS feed

 
Dan Harabox
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've drawn some things on a JPanel. I'd now like to retrieve the graphics (images, shapes, etc) I've drawn on the panel and pass this data to another component to add to it.
If I use the getGraphics() method of the JPanel however I'm returned a NullPointerException. What am I doing wrong?
Here's an example of what I want to do:

I hope this makes sense.
I realise one workaround is to call the paintComponent method of myPanel2 from the paintComponent method of myPanel, passing the graphics down directly, however this ends up getting messy and forces me to store myPanel2 in a location which makes it accessible from myPanel's paintComponent method.
Any help much appreciated.
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the end result you are trying to achieve with this? There are several ways you could multiple layers in a component -

Add the component you are currently painting on to another container that has an overridden paint() method that inserts drawing operations after the paintChildren() method.

Make each layer of the final product a separate image. Draw to each of these images separately and then put them all together in the paintComponent() method of your component.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!