0

Let's say we have the following situation:

JPanel panelp=new JPanel();
paintSomething(panelp.getGraphics();

and somewhere else in a different object, the method:

void paintSomething(Graphics g){ /*code*/ }

I don't want to override paintComponent method of panelp. How can I paint something to panelp from the method paintSomething using the Graphics of panelp?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Claudiu C
  • 95
  • 1
  • 1
  • 11

2 Answers2

4

whatever.getGraphics() is snapshot is the snapshot that will go away when

  • after first repaint

  • JComponets are repainted internally from Mouse or Key Events, these events are implemented in the concrete JComponets API

  • simple example for usage of whatever.getGraphics() is printing to the printer or saving current GUI as printscreen to the e.g. JPEG or PGN File

basic stuff is described in the 2D Graphics

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • +1 You just resolved a question that I had in the back of my head! – GETah Jun 08 '12 at 18:01
  • Oh so is there a method to draw something to a component from outside? – Claudiu C Jun 08 '12 at 18:03
  • 1
    @ClaudiuC: Use a `BufferedImage`, for [example](http://stackoverflow.com/a/2901472/230513). – trashgod Jun 08 '12 at 18:08
  • if you maning from another class, method or void then basically yes no idea what wrong with that, you can put arrays of Object to the paintComponent delayed with Swing Timer, – mKorbel Jun 08 '12 at 18:09
3

You could draw your stuff in the paintSomething into a BufferedImage which you can then draw to the panel by overriding paintComponent

GETah
  • 20,922
  • 7
  • 61
  • 103