Java SWT 从 ListViewer 中删除元素

Java SWT remove element from ListViewer

我正在用 SWT 编写 GUI。您可以通过单击按钮(如浏览)选择 file/s,然后按名称将它们添加到 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);
        }
    });

当您使用像 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);
  }
});