I want to get the names of the checked items when I click on the new button. And unfortunately, I could not fix this problem by adding a listener for items. Is there a solution for this code?
this sample code:
public class SWTTreeExample {
private Shell shell;
public static Tree check;
public void run() {
Display display = new Display();
shell = new Shell(display);
shell.setText("TreeExample");
createContents(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private void createContents(Composite composite) {
composite.setLayout(new GridLayout(1, true));
GridData data = new GridData(GridData.FILL_BOTH);
Button btnNewButton = new Button(shell, SWT.NONE);
btnNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
TreeItem[] items = check.getSelection();
System.out.println(items[0]);
}
});
btnNewButton.setText("New Button");
check = new Tree(composite, SWT.CHECK | SWT.BORDER);
data = new GridData(GridData.FILL_BOTH);
check.setLayoutData(data);
fillTree(check);
}
private void fillTree(Tree tree) {
tree.setRedraw(false);
for (int i = 0; i < 1; i ) {
TreeItem item = new TreeItem(tree, SWT.NONE);
item.setText("Root Item " i);
for (int j = 0; j < 3; j ) {
TreeItem child = new TreeItem(item, SWT.NONE);
child.setText("Child Item " i " - " j);
}
}
tree.setRedraw(true);
}
public static void main(String[] args) {
new SWTTreeExample().run();
}
}
CodePudding user response:
With Tree you need to recurse through the tree looking for checked items. Something like:
private List<String> getChecked(final Tree tree)
{
final List<String> checked = new ArrayList<>();
final TreeItem [] topItems = tree.getItems();
for (final TreeItem item : topItems) {
if (item.getChecked()) {
checked.add(item.getText());
}
addChecked(checked, item);
}
return checked;
}
private void addChecked(final List<String> checked, final TreeItem treeItem)
{
final TreeItem[] items = treeItem.getItems();
for (final TreeItem item : items) {
if (item.getChecked()) {
checked.add(item.getText());
}
addChecked(checked, item);
}
}
Note: The JFace CheckboxTreeViewer is much easier to use for this sort of thing and has a getCheckedElements() method for this.
