Search code examples
javaswinguser-interfacejlistpreferredsize

Preventing JList from auto resizing


I have a JList inside a JScrollPane that's placed in a JPanel (BorderLayout.CENTER) and putting that inside another JPanel's BorderLayout.EAST (this JPanel's CENTER contains another JPanel) and this whole JPanel is placed inside a JTabbedPane. Initially, it would look like this: Initial JList GUI

Now I add some books to the list:

JList with some books in it

If I go to another tab and come back, this happens:

Resized JList

What I don't understand is that, the JPanel containing the JList has both its minimum and maximum size set:

JPanel listPanel = new JPanel();
listPanel.setLayout(new BorderLayout());
listPanel.add(new JScrollPane(bookList), BorderLayout.CENTER);
listPanel.setMinimumSize(listPanel.getPreferredSize());
listPanel.setMaximumSize(listPanel.getPreferredSize());
checkOutPanel.add(listPanel, BorderLayout.EAST);

How can I prevent the JList from auto resizing?


Solution

  • Depending on what it is you trying archive, you can either use JList#setPrototypeCellValue or JList#setFixedCellWidth. These will feed back into the PeferredScrollableViewportSize method which will effect the scroll pane