views:

53

answers:

2

Hi,

is there a possibility to draw a JPanel on a specific location op a Graphics (or Graphics2D) object? I override the paint method of my canvas, and call panel.paint(g) in there, but it does not work the way I woul hope.

@Override
public void paint(Graphics g){
  Dimension size = panel.getPreferredSize();
  panel.setBounds(pos.x, pos.y, size.width, size.height);
  panel.paint(g);
}

the size object is correctly defined as I would wish, so that's not the problem. Also, the pos contains a correct x and y on the screen.

+1  A: 

You should probably be using paintComponent instead of paint, since the latter is the AWT method, and the former is the Swing method.

One nice thing about Swing's paintComponent is that the Graphics passed is actually always going to be a Graphics2D, so you can:

Graphics2D g = (Graphics2D)lg;

Now you can use the getTransform to save the old transform, then modify the transform of the Graphics2D using either setTranform or the scale, translate and rotate methods. Don't forget to restore the old transform, or you'll likely fudge the next thing being drawn by that context.

Kristopher Ives
I replaced the paint by paintComponent, and used the transform to move the panel to another location. But nothing gets painted...
Fortega
A: 

I'll throw in that, depending on the circumstance, drawing to a BufferedImage might be appropriate. You can get a Graphics context using BufferedImage.getGraphics(). Then you can draw the BufferedImage's context by whatever means suit you.

spurserh
Can I convert a panel to a BufferedImage? Or what is the missing link here?
Fortega
maybe createImage(int width, int height)?But this returns null in my case
Fortega