Im writing a class which intends to turn a bufferedimage objects into a graphics2d object so as to make use of the draw() method. Once that's done the method will return the graphics object to the class subclassing a JFrame. This class will position and paint the graphics object onto the JPanel. At least thats the intention but:
I'm stuck painting the graphics object onto the form. Any ideas? casting it back to a bufferedImage and using paintImage() in the paint() method of JPanel looks like an option but im unsure on how to use this method and graphics efficiency is imperative something which [prob] won't benefit of continual casting..
using getGraphics(), casting and passing the Graphics2d fails to fruit when the class calls Draw() on it. It is not a solution I'm interested in anyhow..
I think you have a basic misunderstanding about the relationship between BufferedImage and Graphics. You can't cast one to another. A BufferedImage is an Image that holds its pixel data in memory. A Graphics object is a virtual surface that you can draw on -- it may or may not be backed by a BufferedImage.
One way to set pixels in on a BufferedImage is to use a graphics object. It sounds like you are already doing this:
Once you are done drawing, there is no need to hang onto the graphics object. The usual thing to do is call dispose, but that may be a noop for BufferedImages.
Now how do you show the results of that rendering? You typically do not subclass JFrame, because JFrame is the frame, not the painting, right? Instead, you might use a JLabel to display your BufferedImage:
JLabel label = new JLabel(new ImageIcon(bi));
Or if you are doing tricky things, you may subclass JComponent and override its paintComponent method:
There is no emoticon for what I am feeling!
Joined: Nov 21, 2004
Thank you for your help. It is very much appreciated in circumstances most despairing.
I'll confess. My hours are consumed attempting to create tetris, hence the drawing on the JFrame. I fear losing KeyEvent functionality when adding a label component to the form so I wish to restrain from doing so.
The KeyEvent listener is added to the JFrame subclass.
I am using another class to proxy the graphics rendering, allowing me to create multiple instances, easing the process of implementing [local] multiplayer.
As JPanel is a subclass of the Component class, I can override the paintComponent method there. [?]