Merge branch 'subtree'
[nikiroo-utils.git] / ui / ListSnapshot.java
1 package be.nikiroo.utils.ui;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import javax.swing.JList;
7
8 public class ListSnapshot {
9 private JList list;
10 private List<Object> elements = new ArrayList<Object>();
11
12 public ListSnapshot(JList list) {
13 this.list = list;
14
15 for (int index : list.getSelectedIndices()) {
16 elements.add(list.getModel().getElementAt(index));
17 }
18 }
19
20 public void apply() {
21 applyTo(list);
22 }
23
24 public void applyTo(JList list) {
25 List<Integer> indices = new ArrayList<Integer>();
26 for (int i = 0; i < list.getModel().getSize(); i++) {
27 Object newObject = list.getModel().getElementAt(i);
28 for (Object oldObject : elements) {
29 if (isSameElement(oldObject, newObject)) {
30 indices.add(i);
31 break;
32 }
33 }
34 }
35
36 int a[] = new int[indices.size()];
37 for (int i = 0; i < indices.size(); i++) {
38 a[i] = indices.get(i);
39 }
40 list.setSelectedIndices(a);
41 }
42
43 // You can override this
44 protected boolean isSameElement(Object oldElement, Object newElement) {
45 if (oldElement == null || newElement == null)
46 return oldElement == null && newElement == null;
47
48 return oldElement.toString().equals(newElement.toString());
49 }
50
51 @Override
52 public String toString() {
53 StringBuilder builder = new StringBuilder();
54 builder.append("List Snapshot of: ").append(list).append("\n");
55 builder.append("Selected elements:\n");
56 for (Object element : elements) {
57 builder.append("\t").append(element).append("\n");
58 }
59
60 return builder.toString();
61 }
62 }