设置JList以填充它添加到的组件的整个大小

trs*_*trs 2 java swing jpanel jframe jlist

下面是我创建JList的代码.当它在独立的JFrame中创建时,JList会填充整个框架.但是,当我将其创建为JPanel并将其添加到JFrame时,它没有填充组件的大小,为什么?

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);

}
Run Code Online (Sandbox Code Playgroud)

Kav*_*vka 5

因为默认的布局管理器JFrame内容窗格BorderLayout直接添加到它会填满整个画面的内容窗格中的整个可用空间(即,中心).另一方面,a的默认布局管理器JPanelFlowLayout.所述FlowLayout类放部件成一排,在其优选的大小尺寸.因此添加JList到a JPanel将不会填满整个可用空间.