Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set only the preferred width of Panel with flow layout?

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?

like image 412
Rogach Avatar asked Oct 03 '11 09:10

Rogach


People also ask

What is FlowLayout in Java?

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.

What pattern does the FlowLayout layout manager use to add components to container?

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.

What is JPanel Swing Java?

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.


2 Answers

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.

like image 107
camickr Avatar answered Oct 20 '22 05:10

camickr


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.

like image 44
Heisenbug Avatar answered Oct 20 '22 05:10

Heisenbug