ludc
2024-09-14 36c2449aec5b51e5ed4e5c6841154b746060e09a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.vci.client.ui.tree;
 
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
 
import javax.swing.JCheckBox;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;
 
public class CheckBoxTreeManager extends MouseAdapter implements TreeSelectionListener {
 
    private CheckBoxTreeSelectionModel selectionModel;
    private JTree tree = new JTree();
    int hotspot = new JCheckBox().getPreferredSize().width;
    
    public CheckBoxTreeManager(JTree tree) {
        this.tree = tree;
        selectionModel = new CheckBoxTreeSelectionModel(tree.getModel());
        tree.setCellRenderer(new CheckBoxTreeCellRenderer(tree.getCellRenderer(), selectionModel));
        tree.addMouseListener(this);
        selectionModel.addTreeSelectionListener(this);
    }
    
    public void mouseClicked(MouseEvent me) {
        TreePath path = tree.getPathForLocation(me.getX(), me.getY());
        if (path == null) {
            return;
        }
        if (me.getX() > tree.getPathBounds(path).x + hotspot) {
            return;
        }
        
        boolean selected = selectionModel.isPathSelected(path, true);
        selectionModel.removeTreeSelectionListener(this);
        
        try {
            if (selected) {
                selectionModel.removeSelectionPath(path);
            } else {
                selectionModel.addSelectionPath(path);
            }
        } finally {
            selectionModel.addTreeSelectionListener(this);
            tree.treeDidChange();
        }
    }
    
    public CheckBoxTreeSelectionModel getSelectionModel() {
        return selectionModel;
    }
    
    public void valueChanged(TreeSelectionEvent e) {
        tree.treeDidChange();
    }
}