Skip to content

Instantly share code, notes, and snippets.

@LoganBarnett
Created January 3, 2009 01:13
Show Gist options
  • Save LoganBarnett/42760 to your computer and use it in GitHub Desktop.
Save LoganBarnett/42760 to your computer and use it in GitHub Desktop.
package swing;
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.DefaultTreeSelectionModel;
import javax.swing.tree.TreePath;
public class CheckTreeManager extends MouseAdapter implements TreeSelectionListener{
private DefaultTreeSelectionModel selectionModel;
private JTree tree = new JTree();
int hotspot = new JCheckBox().getPreferredSize().width;
public CheckTreeManager(JTree tree){
this.tree = tree;
selectionModel = new DefaultTreeSelectionModel();// (tree.getModel());
selectionModel.setSelectionMode(DefaultTreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
tree.setCellRenderer(new CheckTreeCellRenderer(tree.getCellRenderer(), selectionModel));
tree.addMouseListener(this);
selectionModel.addTreeSelectionListener(this);
}
public void mouseClicked(MouseEvent me){
if (1 < me.getClickCount()) return;
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);
selectionModel.removeTreeSelectionListener(this);
try{
if(selected)
selectionModel.removeSelectionPath(path);
else
selectionModel.addSelectionPath(path);
} finally{
selectionModel.addTreeSelectionListener(this);
tree.treeDidChange();
}
}
public DefaultTreeSelectionModel getSelectionModel(){
return selectionModel;
}
public void valueChanged(TreeSelectionEvent e){
tree.treeDidChange();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment