JList中的多个区间选择

时间:2015-11-13 20:18:27

标签: selection jlist

我希望从JList中选择多个(" columns")。如何在JList中获取所有选定项的String值,并在按下一个(" Export")按钮后将它们放入Strings的数组/ ArrayList中?

我在构造函数中有这个:

public ColumnList(String[] allColumns) {
    super(new BorderLayout());
    listModel = createListModel(allColumns); // contains all the columns
    list = new JList<String>(listModel);
    list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    list.setSelectedIndex(0);
    list.setVisibleRowCount(5);
    JScrollPane listScrollPane = new JScrollPane(list);
    exportButton = createExportButton(exportString);
}

同一类是这个内部类:

class ExportListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        String columnName = (String) list.getSelectedValue();
        selectedCols.add(columnName); // add to array list
    }
}

现在我知道这不起作用。这只适用于一个选定的值。如何进行多项选择?

2 个答案:

答案 0 :(得分:0)

class ExportListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        String[] columnsSelected;
        columnsSelected = new String[list.getSelectedValuesList().size()];
        columnsSelected = (list.getSelectedValuesList()).toArray(columnsSelected);      
    }
}

我能够这样做。

答案 1 :(得分:0)

在调用JList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)后使用JList.setSelectedIndices(int [])

jList.setSelectionMode(
        ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    int[] selectIndices = {0, 3};
jList.setSelectedIndices(selectIndices);