Change the height of a panel at runtime
How to change the height of panel at runtim开发者_开发知识库e?
I have some panels inside a JFrame
, I tried on one of them:
int w = panel.getWidth();
panel.setSize(w, 1000);
But there's no effect. What's wrong?
You may have to validate and repaint your panel. Try following:
int x=panel.getWidth();
panel.setSize(x,1000);
panel.validate();
panel.repaint();
Check out this answer:
set size wont work in java
"In Swing, you have two options for layout: do everything manually or let a LayoutManager handle it for you."
and
"Try calling setPreferredSize() and setMinimumSize()."
If you are using a layout manager (you probably are), the layout decides what to do with the contained components. setPreferredSize() usually works because the layout usually asks the contained components what their preferred sizes are, and then arranges the components based on (among others) that information.
If you put the panel in a LayoutManager (i.e. the parent has a LayoutManager which is BorderLayout by default) that LayoutManager would override the size and thus your call would have no effect.
Try to call setLayoutManager(null)
on the parent although I'd recommend using a LayoutManager and use setPreferredSize()
, setMinimumSize()
and setMaximumSize()
.
For changing width and height of JPanel use setPreferredSize method.
JPanel folderPanel = new JPanel();
folderPanel.setPreferredSize(new Dimension(245, 450));// width, height
You just set the visibility of this component (JPanel) as follow:
JPanel panel = new JPanel();
//set your custom size in this with=120; height=570;
panel.setSize(120,570);
panel.setVisible(false);
panel.setVisible(true);
//hope this help! :)
精彩评论