设置 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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为
JFrame
的 内容窗格 的默认布局管理器是BorderLayout
,直接添加到它会填充整个可用空间(即中心) 框架的内容窗格。另一方面,JPanel
的默认布局管理器是FlowLayout
。 FlowLayout 类将组件排成一行,并按其首选大小调整大小。因此,将JList
添加到JPanel
不会填充整个可用空间。Because the default layout manager of a
JFrame
's content pane isBorderLayout
and 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 aJPanel
isFlowLayout
. TheFlowLayout
class puts components in a row, sized at their preferred size. So adding theJList
to aJPanel
would not fill the entire available space.我从@kavka 得到了答案......事实是更改边框布局。
From @kavka I derived the answer... The fact is Change to Border Layout.