Matei Focseneanu
Matei Focseneanu

Reputation: 103

How can I have a JScrollPane fill the height of a JPanel

I'm starting with Java and Swing, so I have a very simple question but I just can't find any (simple) way to solve it...

What I mean is just have a list scroller that occupy the whole height of a panel, nothing more. Here is the code I already wrote, thanx to help me to find a way to achieve my goal:

public class TestCode {

public static void main(String[] args) {

    JFrame window = new JFrame("Test");
    window.setSize(300, 300);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panelUp = new JPanel();
    JPanel panelCenter = new JPanel();
    JPanel panelDown = new JPanel();

    window.add(panelUp, BorderLayout.NORTH);
    window.add(panelCenter, BorderLayout.WEST);
    window.add(panelDown, BorderLayout.SOUTH);

    panelUp.setBackground(new Color(200, 240, 200));
    panelCenter.setBackground(new Color(240, 200, 200));
    panelDown.setBackground(new Color(200, 200, 240));

    Vector v = new Vector();
    v.addElement("Element 1");
    v.addElement("Element 2");
    v.addElement("Element 3");
    v.addElement("Element 4");
    v.addElement("Element 5");
    v.addElement("Element 6");

    JList list = new JList(v);
    JScrollPane listScroller = new JScrollPane(list);

    panelCenter.add(listScroller);

    window.setVisible(true);
}

}

Upvotes: 1

Views: 6769

Answers (2)

Harald K
Harald K

Reputation: 27064

You don't really need panelCenter, just add listScroller directly to the root pane, using window.add(listScroller, BorderLayout.CENTER). It's important to use CENTER if you want to fill the entire space of a component with BorderLayout. See the tutorial on BorderLayout for more info.

If you want to keep panelCenter, make sure you explicitly give it a BorderLayout. The default layout for JPanel is FlowLayout.

I would use:

JPanel panelCenter = new JPanel(new BorderLayout());

Upvotes: 3

Nick Holt
Nick Holt

Reputation: 34311

The default layout for a JPanel is a FlowLayout, for a control to be centered and fill a JPanel you need to use the BorderLayout. Try this:

panelCenter.setLayout(new BorderLayout());
panelCenter.add(listScroller, BorderLayout.CENTER);

Upvotes: 9

Related Questions