JScrollPane: How to resize automatically the JPanel contained in the scroll
I'm working on a little applet that has a list of items in a JScrollPane on the left.
the user will be able to add and remove elements from this list.
therefore I need to create a scrollable list.
this part is easy.
I'm usually tempted to do most of the GUI resizing by hand but I read in the doc of the JScrollPane that it is better to let swing handle it rather than manually changing the dimension.
the problem is that I keep adding element and 开发者_如何学Pythonthe inside panel doesn't change size.
any ideas?
here is some of the code I'm using: constructor:
public SideBarView(Dimension d) {
super(d);
Dimension d2 = new Dimension(100,300);
this.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
//INSIDE VIEW (zone that is being scrolled)
container = new SideBarContainer(d2);
// container.setSize(d2);
// container.setPreferredSize(d2);
// container.setMaximumSize(d2);
// container.setMinimumSize(d2);
scrollPane = new MyJScrollPane(container);
new ImageLoaderWorker(this,menuButton).execute();
Dimension d3 = new Dimension(d.width, d.height-d.width);
scrollPane.setSize(d3);
scrollPane.setMaximumSize(d3);
scrollPane.setMinimumSize(d3);
scrollPane.setPreferredSize(d3);
add(scrollPane,BorderLayout.PAGE_START);
setBorder(BorderFactory.createEmptyBorder());
}
Adding to container:
element = new JPanel();
Dimension d2 = new Dimension(100,100);
element.setSize(d2);
element.setPreferredSize(d2);
element.setMaximumSize(d2);
element.setMinimumSize(d2);
element.setBackground((panelcount++%2==0)?Color.BLUE:Color.RED);
cointainer.add(element);
any idea what I'm missing ? or should I just resize the container by hand as I go along?
You need to tell the container to lay out the components. This is done by revalidating the panel:
container.add(element);
container.revalidate();
panel.setSize(d2);
panel.setPreferredSize(d2);
panel.setMaximumSize(d2);
panel.setMinimumSize(d2);
This let's no option to resize for swing, since you tell the layout manager to use exactly the size of d2 (100/100).
Try without setMaximumSize
and setPreferredSize
. You might need to invalidate the panel or scrollpane after adding/removing content as well.
Edit:
I think I considered panel
to be your containter. Could you provide the setup code for your scrollpane and the container?
Did you set a layout manager for the container?
Another possibility, if you don't have to do it yourself, could be to use some SwingX component (like TaskPane etc.). Unfortunately, they seem to be in a transition over to java.net and thus many resources are not available as of now. However, there's a basic download page.
精彩评论