1

I want to resize child components related to its parent(Panel).

I am using the following method:

@Override
public Dimension getPreferredSize() {
Dimension d = getParent().getSize();
int w = d.width * wid / 100;
int h = d.height * he / 100;
//System.out.println("x"+w+"h"+h);
return new Dimension(w,h);
}

But it doesn't solve my problem. Can anybody tell if there is another way to resize component?

Avant Garde
  • 220
  • 2
  • 9
Babu R
  • 1,025
  • 8
  • 20
  • 40

2 Answers2

3
  • use proper LayoutManager, no reason to supply that

  • in the case that you want to resize programaticaly, by refusing LayoutManager, then you have to implement ComponentListener or HierarchyListener

  • after any (above mentioned) changes you have to call revalidate() and repaint()

  • if you want to resize from any Listener, delay resize (400-500 miliseconds) event by Swing Timer, if resize continue Timer#restart() to avoiding flickering or freeze,

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
mKorbel
  • 109,525
  • 20
  • 134
  • 319
0

You can just call the setPreferredSize(Dimension d) on the child components. If you pack the JFrame, the components will try to become that size.


EDIT: As the comment said, it is best to avoid setPreferredSize(Dimension d), but I have had uses for the method. For example: A JPanel with a BorderLayout, in which you have 3 JPanels (custom classes). The WEST and SOUTH Panel (the other is CENTER) had to have a height of 0.1 * the width or the height respectively if the JPanel. I used

setPreferredSize(new Dimension(getPreferredSize().height, getPreferredSize().width * 0.1))

which worked well. The Borderlayout took that value, and made the Panel a bit wider (I had to do this because there were no other JComponents in any of the inner JPanels).

Hidde
  • 11,493
  • 8
  • 43
  • 68
  • In general, using `setPreferredSize()` this way is a [_bad idea_](http://stackoverflow.com/q/7229226/230513). – trashgod May 28 '12 at 12:56
  • Invoking `pack()` on the `WEST` and `SOUTH` panels should cause them to adopt the size required to display the enclosed components, each of which should calculate its own preferred size. This is critical if the content includes text. – trashgod May 28 '12 at 14:00
  • I mentioned in my edit that there are NO components in the WEST, SOUTH or CENTER JPanels. I use them to draw on. – Hidde May 28 '12 at 14:12
  • Ah, that make's sense; overriding `getPreferredSize()` to reflect the drawing's geometry is also an option. Edit: I suspect OP is using `ChartPanel`; this may be a useful approach in conjunction with constructor parameters. Without more information, we're all guessing. – trashgod May 28 '12 at 15:14