Reputation: 55
I am painting on a Panel by overriding the paintComponent -method.
class Canvas extends Panel ...
...
override def paintComponent(g: Graphics2D) {
super.paintComponent(g)
for (cmd <- commands.get) cmd.execute(g, this)
}
Okay. Inside one of the commands is this one.
case class TestCommand() {
def execute(g: java.awt.Graphics2D, c: Canvas) = {
val img = new BufferedImage(c.width, c.height, BufferedImage.TYPE_INT_RGB)
g.drawImage(img, null, 0, 0)
}
What im trying to do there is create a BufferedImage from the Graphics2D -object, so i can read the value of some pixel at location x, y.
However when this command is executed, i notice that the drawImage -method causes my panel to turn completely black, wiping everything i've drawn on it so far. I want the command to simply create a BufferedImage of what i've drawn on the panel, instead of somehow affecting the Graphics2D -object itself. What am i doing wrong here?
Upvotes: 1
Views: 2096
Reputation: 37875
A Graphics2D
is connected to some canvas or image. You might think of it like a brush or a pen. In this case, the graphics object you have is tied to your panel. Calling drawImage
draws the image on to the panel.
If you want to draw the panel on to the image, you need a Graphics
for the BufferedImage
:
Graphics2D ig = img.createGraphics();
Then you need to paint the panel to the graphics. java.awt.Component
provides a number of convenience methods for this type of thing, for example printAll
:
c.printAll(ig);
ig.dispose(); // don't forget to dispose Graphics you've created
(Sorry, I don't really know Scala syntax, if it's different.)
Without being too presumptuous, there may be better ways to approach what you're doing. E.g. if you're doing painting to the panel, as mentioned in the comments, it's usually a good idea to do your painting on an image to begin with, then paint the image to the panel. Then you always have the image.
Upvotes: 3