Java SWT从ListViewer删除元素

时间:2018-07-04 10:19:39

标签: java swt jface

我正在用SWT编写GUI。您可以通过单击按钮(例如“浏览”)选择文件,然后按名称将它们添加到ListViewer。我创建了一个新按钮来从列表中删除文件,但是它对我不起作用。 我猜这是所需的代码段:

    ListViewer listViewer = new ListViewer(shlPmcompare, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
    List list = listViewer.getList();
    list.setBounds(331, 11, 305, 100);

    btnBrowse.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            FileDialog fileBrowse = new FileDialog(shlPmcompare, SWT.MULTI);
            fileBrowse.setFilterExtensions(new String[] {"*.txt"});
            String filePath = fileBrowse.open();
            if (filePath != null) {
                StringBuffer buf = new StringBuffer();
                String[] files = fileBrowse.getFileNames();
                for (int i = 0, n = files.length; i < n; i++) {
                  buf.append(fileBrowse.getFilterPath());
                  if (buf.charAt(buf.length() - 1) != File.separatorChar) {
                    buf.append(File.separatorChar);
                  }
                  buf.append(files[i]);
                  buf.append("\n");
                }
                for (int i = 0, n = files.length; i < n; i++) {
                    list.add(files[i], 0);
                }
            }
        }
    });

    btnRemoveFile.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            IStructuredSelection selectionFile = (IStructuredSelection)listViewer.getSelection();
            List RemoveFile = (List)selectionFile.getFirstElement();
            if(RemoveFile == null) {
                MessageDialog.openError(shlPmcompare, "Removing Error", "You need to select file first.");
                return;
            }
            list.remove(RemoveFile);
            listViewer.refresh(false);
        }
    });

1 个答案:

答案 0 :(得分:3)

在使用ListViewer之类的JFace查看器时,除少数例外,您不应在基础控件上调用任何方法(在这种情况下为List)。查看器管理该控件,您只应使用查看器的方法对其进行更改。

要从列表中删除选择,请调用ListViewer remove方法, List.remove

这是一个只显示一些字符串的查看器:

ListViewer listViewer = new ListViewer(shell, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
listViewer.getList().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

listViewer.setContentProvider(ArrayContentProvider.getInstance());

ArrayList<String> contents = new ArrayList<>();
contents.add("a");
contents.add("b");
contents.add("c");

listViewer.setInput(contents);

Button btnRemoveFile = new Button(shell, SWT.PUSH);
btnRemoveFile.setText("Remove");
btnRemoveFile.addSelectionListener(new SelectionAdapter() {
  @Override
  public void widgetSelected(final SelectionEvent e) {
      IStructuredSelection selectionFile = listViewer.getStructuredSelection();
      final Object removeFile = selectionFile.getFirstElement();
      // TODO check for no selection

      listViewer.remove(removeFile);

      contents.remove(removeFile);
  }
});