【问题标题】:Cannot add to a JList when list is added to a JScrollPane将列表添加到 JScrollPane 时无法添加到 JList
【发布时间】:2016-03-23 04:41:44
【问题描述】:

我编写了一个程序来选择文件并将它们添加到 JList。程序运行良好,将文件添加到列表的代码如下:

JPanel pane;
File newFile[];
static List<File> files = new ArrayList<File>();
static DefaultListModel<File> listModel = new DefaultListModel<>();
JList<File> fileList = new JList<>(listModel);

JPanel listPane = new JPanel();
pane.add(listPane, BorderLayout.CENTER);
listPane.setBackground(Color.LIGHT_GRAY);
listPane.setBorder(new EmptyBorder(0, 20, 0, 0));
listPane.setLayout(new BorderLayout());
listPane.add(fileList);
}
void getFile() {
    final JFileChooser fc = new JFileChooser();
    fc.setDialogTitle("Select File...");
    fc.setApproveButtonText("Select");
    fc.setMultiSelectionEnabled(true);
    int returnVal = fc.showOpenDialog(pane);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        newFile = fc.getSelectedFiles();
    }
}
void setFile() {
    int i = 0;
    while (i < newFile.length) {
        files.add(newFile[i]);
        listModel.addElement(newFile[i]);
        i++;
    }
}

这是选择和添加文件的基本代码。所以现在我想在窗格上有一个滚动条,所以我将它修改为这样的 JScrollPane:

JScrollPane listPane = new JScrollPane();
pane.add(listPane, BorderLayout.CENTER);
listPane.setBackground(Color.LIGHT_GRAY);
listPane.setBorder(new EmptyBorder(0, 20, 0, 0));
listPane.setViewportView(fileList);
listPane.add(fileList);
}

所以一切都编译没有错误,但没有添加到 JScrollPane。我的理解是 JScrollPane 可以像普通的 JPanel 一样使用,只是它在溢出时会有滚动条。我在这里缺少关于 JScrollPanes 的一些东西吗?

【问题讨论】:

  • 建议: 1) 在创建滚动窗格并将其添加到 GUI 时,将列表添加到滚动窗格。 2)此后,只处理(添加项目或从中删除)模型。 3)删除static List&lt;File&gt; files = new ArrayList&lt;File&gt;();并直接从模型中获取任何信息或File。 4) 从static DefaultListModel&lt;File&gt; listModel = new DefaultListModel&lt;&gt;(); 中删除static 前缀。静态很少是正确的解决方案(无论问题是什么)。 5) 为了尽快获得更好的帮助,请发帖minimal reproducible exampleShort, Self Contained, Correct Example

标签: java swing jscrollpane jlist defaultlistmodel


【解决方案1】:

尝试删除

listPane.add(fileList); //remove

您应该使用setViewportView() 方法将组件添加到滚动窗格。您已经完成了。所以您不需要通过调用listPane.add 再次添加。

例子

JScrollPane listPane = new JScrollPane();
pane.add(listPane, BorderLayout.CENTER);
listPane.setBackground(Color.LIGHT_GRAY);
listPane.setBorder(new EmptyBorder(0, 20, 0, 0));
listPane.setViewportView(fileList);
// removed add line

您也可以通过传递给滚动窗格构造函数来传递要添加到滚动窗格的组件,如 thompson 所说。

JScrollPane listPane = new JScrollPane(fileList);

正如汤普森所说,你应该避免声明 listModel ,files 。你应该阅读更多关于 static keyword and when you should use it 的信息。

【讨论】:

  • 我更喜欢JScrollPane listPane = new JScrollPane(fileList); // add the only component this scroll pane will ever show, at time of construction(也许没有冗长的评论)。 ;)
  • 做到了。此外,为了进一步简化它,我尝试了 Andrew 的建议,将其添加到 JScrollPane 构造函数中,这也有效。两个很棒的解决方案。谢谢大家。
猜你喜欢
  • 2017-03-03
  • 2012-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
  • 2015-11-11
相关资源
最近更新 更多