Reputation: 1035
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?
Upvotes: 1
Views: 2612
Reputation: 11961
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).
Upvotes: 0
Reputation: 109823
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,
Upvotes: 3