below is my code for creating the JList. When it is created in a standalone JFrame the JList fills the entire frame. However, when I create it as a JPanel and add it to the JFrame it is not filling the size of the component, Why?
public class ListBranchesInterface extends JPanel {
private Library theLibrary; // reference to back end
private ArrayList<LibraryBranch> branches;
private DefaultListModel dlm;
private JList list;
private JScrollPane scroll;
public ListBranchesInterface(Library theLibrary) {
this.theLibrary = theLibrary;
branches = new ArrayList<LibraryBranch>();
branches.addAll(theLibrary.getLibraryBranches());
Iterator<LibraryBranch> iter = branches.iterator();
dlm = new DefaultListModel();
while (iter.hasNext()) {
dlm.addElement(iter.next().toString());
}
list = new JList(dlm); // create a JList from the default list model
scroll = new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); // add a scroll pane
// to the JList
add(scroll);
setVisible(true);
}
Because the default layout manager of a
JFrame‘s content pane isBorderLayoutand adding directly to it would fill the entire available space (i.e., center) of the frame’s content pane. On the other hand, the default layout manager of aJPanelisFlowLayout. TheFlowLayoutclass puts components in a row, sized at their preferred size. So adding theJListto aJPanelwould not fill the entire available space.