I have a panel with flow layout, and it can contain a variable number of items - from 1 to 2000. I want to put it inside a scroll pane, scrollable in vertical direction, and with fixed width. The problem is, when I set preferred size of panel to something like (800,600), some items are missing, and there is no scroll. If I set up preferred size of scroll pane, then all elements in flow pane are put on one very long line.
Setting maximum size on any element seems to do nothing at all - layout managers ignore it.
How can I fix this?
A flow layout arranges components in a directional flow, much like lines of text in a paragraph. The flow direction is determined by the container's componentOrientation property and may be one of two values: ComponentOrientation. LEFT_TO_RIGHT. ComponentOrientation.
FlowLayout is a simple layout manager that tries to arrange components with their preferred sizes, from left to right and top to bottom in the container. A FlowLayout can have a specified row justification of LEFT , CENTER , or RIGHT , and a fixed horizontal and vertical padding.
JPanel, a part of the Java Swing package, is a container that can store a group of components. The main task of JPanel is to organize components, various layouts can be set in JPanel which provide better organization of components, however, it does not have a title bar.
I want to put it inside a scroll pane, scrollable in vertical direction, and with fixed width
You can use the Wrap Layout for this.
Don't set the preferred size of the panel. But you can set the preferred size of the scroll pane so the frame.pack() method will work.
You could use BoxLayout to do this:
JPanel verticalPane = new JPanel();
verticalPane.setLayout(new BoxLayout(verticalPane, BoxLayout.Y_AXIS));
JScrollPane pane = new JScrollPane(verticalPane);
//add what you want to verticalPane
verticalPane.add(new JButton("foo"));
verticalPane.add(new JButton("bar"));
This of course will use the preferred size of each component added. If you want to modify the preferred size for example of a JPanel, extend it and override getPreferredSize:
class MyPanel extends JPanel(){
public Dimension getPreferredSize(){
return new Dimension(100,100);
}
}
A note: BoxLayout will take in consideration getPreferredSize, other LayoutManager may not.
Please criticize my answer, I'm not sure it's completely correct and I'm curious to hear objections in order to know if I understood the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With