打印JList的所有内容作为输出

时间:2014-12-07 15:48:02

标签: java swing user-interface jlist

我的GUI中有一个JList,它使用ArrayList作为数据:

    ArrayList Cruise = new ArrayList();
    Cruise.add("Scottish to Greek Waters");
    Cruise.add("Greek to Scottish Waters");

    JScrollPane scrollPane = new JScrollPane();
    CruiseList = new JList(Cruise.toArray()); 
    CruiseList.setPreferredSize(new Dimension(200, 200));
    scrollPane.setViewportView(CruiseList);
    CruiseList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    CruiseList.setSelectedIndex(0);
    CruiseList.setVisibleRowCount(6);
    listPanel.add(scrollPane);
    Frame1.setVisible(true);

我有一个按钮 - 列出所有游轮,一旦点击就应该显示为输出:

"Scottish to Greek Waters"
"Greek to Scottish Waters"

但是,单击该按钮后,它仅显示选定的列表选项作为输出。

这是我到目前为止所做的:

listallCruises.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        String AllCruises = CruiseList.getSelectedValue().toString();
        System.out.print("All Cruises:\n" + AllCruises + CruiseList.getModel() + "\n");
    }
});

单击按钮后如何打印列表中的所有元素?

1 个答案:

答案 0 :(得分:1)

您正在输出所选的值,因为这是您要调用的方法getSelectedValue()

要显示所有值,您必须获取模型并迭代值,如下所示:

int size = CruiseList.getModel().getSize();
StringBuilder allCruises = new StringBuilder("All cruises:");
for(int i = 0; i < size; i++) {
    allCruises.append("\n").append(CruiseList.getModel().getElementAt(i));
}
System.out.print(allCruises);