Ok iDoki
Ok iDoki

Reputation: 79

Java JScrollPane and FlowLayout

After I got such great help yesterday from on of the users on this site, I decided to ask another question here and hope that you guys can help me. I want to code a frame that has components in them.They need to be on a JPanel and that JPanel should be in a JScrollPane.

Now, the problem is that I need to use a FlowLayout for the Panel, because I dont know how many components there will be in my Panel.

If I use a FlowLayout inside a JScrollPane, it does not create a new row, but rather just goes horizontally, which looks super weird in an actual application. What I do want is that, if the window is ending, a new line approaches.

The question is how to solve this. I cant put a preferredSize, because the vertical ScrollBar will not go further than I put the preferredSize to, so I dont really know what to do...maybe change the Layout? I would appreciate any help!

Sample code of the problem:

public class scroller extends JFrame {

    Container c;
    JPanel p;
    JScrollPane pane;
    JButton button1;
    JButton button2;
    JButton button3;
    JButton button4;

    public scroller() {
        c = getContentPane();
        c.setLayout(new BorderLayout());
        p = new JPanel();
        p.setLayout(new FlowLayout());
        pane = new JScrollPane(p);
        button1 = new JButton("OK1");
        p.add(button1);
        button2 = new JButton("OK2");
        p.add(button2);
        button3 = new JButton("OK3");
        p.add(button3);
        button4 = new JButton("OK4");
        p.add(button4);
        p.setVisible(true);
        c.add(pane,BorderLayout.CENTER);

    }

    public static void main(String[] args) {
        scroller window = new scroller();
        window.setSize(200,200);
        window.setVisible(true);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    }   
}

Upvotes: 2

Views: 2667

Answers (1)

camickr
camickr

Reputation: 324118

I cant put a preferredSize, because the vertical ScrollBar will not go further than I put the preferredSize

Correct, the preferredSize() needs to be dynamically calculated as components are added to the panel. The default preferred size calculation for a FlowLayout assumes a single row of components.

So the solution is to use a different layout manager.

The WrapLayout extends FlowLayout and overrides the preferred size calculation to give the preferred width and height as components wrap to a new row.

Upvotes: 2

Related Questions