【问题标题】:set JList to fill the entire size of the component it is added to设置 JList 以填充它添加到的组件的整个大小
【发布时间】:2011-12-25 21:56:28
【问题描述】:

下面是我创建 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);

}

【问题讨论】:

  • (JPanel.)setVisible(true) 对于添加到可见容器的任何组件,默认情况下都会发生这种情况(例如,一旦调用了 setVisible(true),就会出现 JFrame)。

标签: java swing jframe jpanel jlist


【解决方案1】:

因为JFrame内容窗格 的默认布局管理器是BorderLayout,直接添加到它会填满框架内容窗格的整个可用空间(即中心)。另一方面,JPanel 的默认布局管理器是FlowLayoutFlowLayout 类将组件排成一排,按照它们的首选大小调整大小。因此,将 JList 添加到 JPanel 不会填满整个可用空间。

【讨论】:

    【解决方案2】:

    从@kavka 我得出了答案...事实是更改为边框布局。

    JPanel As_list_panel = new JPanel();
    As_list_panel.setBounds(0, 0, 200, 200);    //I think this line is unecessary. check it                                      
    As_list_panel.setLayout(new BorderLayout(0, 0));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 2022-01-09
      • 1970-01-01
      • 2017-09-20
      • 2014-06-12
      相关资源
      最近更新 更多