views:

715

answers:

1

How can i center image when i resize jpanel in swing ? my initial state of the Jpanel that its fits the size of the image ( with pack() ) but now when i resize the Jpanel with my mouse i will like to maintain the image in the center of the Jpanel relative to the Jpanel size

+2  A: 

Either:

  1. Easiest way is probably to use a border layout manager and add a Label with an image to the center. The layout manager will take care of changes.

  2. If you wish to draw the image manually (eg on paint()) you need to add a component listener and call repaint() on any component size change.

Pool
why do i need Label here and border ? can't i just recalculate the size of the image and the Jlable on the resize listener ?
Yes, you can, that's the way described in the second paragraph. I'll edit to make it clear it's two different options.
Pool
+1 for letting a JLabel handle it for you. Someone's already done all the hard work.
banjollity