Toggle JTree nodes

I want to unselect the a tree node , if we select/clicked on already a selected node. Is it possible to do this.
Computer07Asked:
Who is Participating?
 
for_yanCommented:
The above code will always deelect everything when you click
the tree seciond time. You can of couese be more specific and analyze
if you click on the different node then you want keep the selection.
You can determine which node is selected form the location of MoseEvent
and then translate it to the node using getPathForLocation(me.getX(), me.getY());
Then using isPathSelected method of TreeSelectionModel
http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/tree/DefaultTreeSelectionModel.html#isPathSelected%28javax.swing.tree.TreePath%29
you can compare if it is the same node and desleect everything if it is the same node
or sleect new node, if new click was on different node.
0
 
for_yanCommented:
Sure you can do it

This coe provides example:

package components;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.HashMap;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.*;

public class BookTree {
   static HashMap m;
   // DefaultTreeSelectionModel sm = new DefaultTreeSelectionModel();
	public static void main(String args[]) {
		JFrame frame = new JFrame("Book Tree");
		Book javaBooks[] = {
				new Book("Core Java 2 Fundamentals", "Cornell/Horstmann",
						42.99f,"1"),
						new Book("Taming Java Threads", "Holub", 34.95f,"2"),
						new Book("JavaServer  Pages", "Pekowsky", 39.95f,"3") };
		Book htmlBooks[] = { new Book("Dynamic HTML", "Goodman", 39.95f,"4"),
				new Book("HTML 4 Bible", "Pfaffenberger/Gutzman", 49.99f,"5") };
		Vector javaVector = new NamedVector("Java Books", javaBooks);
		Vector htmlVector = new NamedVector("HTML Books", htmlBooks);
		Object rootNodes[] = { javaVector, htmlVector };
		Vector rootVector = new NamedVector("Root", rootNodes);
          m = new HashMap();
		MyJTree tree = new MyJTree(rootVector,m);
       // DefaultTreeSelectionModel sm = new DefaultTreeSelectionModel();
       // tree.setSelectionModel(sm);
           //m = new HashMap();
		TreeCellRenderer renderer = new BookCellRenderer(m);

		tree.setCellRenderer(renderer);
		JScrollPane scrollPane = new JScrollPane(tree);
		frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
		frame.setSize(300, 300);
		frame.setVisible(true);
	}
}

class MyJTree extends JTree implements MouseListener {
    HashMap m;
                     DefaultTreeSelectionModel sm = new DefaultTreeSelectionModel();
    boolean selected;
  public MyJTree(Vector v, HashMap m){
      super(v);
      this.addMouseListener(this);
      this.m = m;
       // DefaultTreeSelectionModel sm = new DefaultTreeSelectionModel();
        this.setSelectionModel(sm);

  }



public void mouseClicked(MouseEvent me) {

                         // if(sm.getSelectionPaths() != null)
                  if(selected){ sm.clearSelection();
                      selected = false;
                  }
                        else
                  selected = true;

       TreePath tp = this.getPathForLocation(me.getX(), me.getY());
      System.out.println("x:" + me.getX() + "  y: " + me.getY());
      //  System.out.println(tp.toString());
     DefaultMutableTreeNode node = null;
    if(tp != null)
    node = (DefaultMutableTreeNode)
         tp.getLastPathComponent();
    else return;

   

               components.Book nodeInfo = null;
             if(node.getUserObject() instanceof components.Book)  {
       nodeInfo =  (components.Book)node.getUserObject();
      System.out.println(nodeInfo.getPrice());
                 if(m.get(nodeInfo.getId()) == null)return;
                 System.out.println((Integer)m.get(nodeInfo.getId()));
                      if (me.getX()-35 >  ((Integer)m.get(nodeInfo.getId())).intValue()){
                          System.out.println("button clicked");
                      }
             }


}
public void mousePressed(MouseEvent me) {

}

public void mouseExited(MouseEvent me) {}

public void mouseEntered(MouseEvent me) {}

    public void mouseReleased(MouseEvent me) {}


}

class Book {
	String title;

	String authors;

	float price;
    String id;

	public Book(String title, String authors, float price, String id) {
		this.title = title;
		this.authors = authors;
		this.price = price;
        this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public String getAuthors() {
		return authors;
	}

	public float getPrice() {
		return price;
	}
public String getId() {
		return id;
	}

}

class BookCellRenderer implements TreeCellRenderer {
  //  MyJTree mtree;
	JLabel titleLabel;

	JLabel authorsLabel;

	JButton priceLabel;

	JPanel renderer;

	DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer();

	Color backgroundSelectionColor;

	Color backgroundNonSelectionColor;
    HashMap m;


	public BookCellRenderer(HashMap m) {
        this.m = m;
       // this.mtree = tree;
		renderer = new JPanel(new GridLayout(1, 3));
		titleLabel = new JLabel(" ");
		titleLabel.setForeground(Color.blue);
		renderer.add(titleLabel);
		authorsLabel = new JLabel(" ");
		authorsLabel.setForeground(Color.blue);
		renderer.add(authorsLabel);
		priceLabel = new JButton("ok");
		priceLabel.setHorizontalAlignment(JLabel.RIGHT);
		priceLabel.setForeground(Color.red);
		renderer.add(priceLabel);
		renderer.setBorder(BorderFactory.createLineBorder(Color.black));
		backgroundSelectionColor = defaultRenderer
		.getBackgroundSelectionColor();
		backgroundNonSelectionColor = defaultRenderer
		.getBackgroundNonSelectionColor();
		priceLabel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.out.println("Button is clicked");
			}
		});
	}

	public Component getTreeCellRendererComponent(JTree tree, Object value,
			boolean selected, boolean expanded, boolean leaf, int row,
			boolean hasFocus) {

		Component returnValue = null;
		if ((value != null) && (value instanceof DefaultMutableTreeNode)) {
			Object userObject = ((DefaultMutableTreeNode) value)
			.getUserObject();

			if (userObject instanceof Book) {
				Book book = (Book) userObject;
				if(book.getTitle().equals("Core Java 2 Fundamentals")){
					titleLabel.setText(book.getTitle());
					authorsLabel.setText(book.getAuthors());
					priceLabel.setText("" + book.getPrice());

                   // priceLabel.addMouseListener(mtree);
                   // renderer.addMouseListener(mtree);
					if (selected) {
						renderer.setBackground(backgroundSelectionColor);
					} else {
						renderer.setBackground(backgroundNonSelectionColor);
					}
					renderer.setEnabled(tree.isEnabled());
                     System.out.println(book.getId() + " " + priceLabel.getWidth() + " " + authorsLabel.getWidth() + " " + titleLabel.getX()) ;
                      m.put(book.getId(), new Integer(priceLabel.getWidth()  + authorsLabel.getWidth()));
					returnValue = renderer;
				}
                			if(book.getTitle().equals("Taming Java Threads")){
					titleLabel.setText(book.getTitle());
					authorsLabel.setText(book.getAuthors());
					priceLabel.setText("" + book.getPrice());

                   // priceLabel.addMouseListener(mtree);
                   // renderer.addMouseListener(mtree);
					if (selected) {
						renderer.setBackground(backgroundSelectionColor);
					} else {
						renderer.setBackground(backgroundNonSelectionColor);
					}
					renderer.setEnabled(tree.isEnabled());
                            System.out.println(book.getId() + " " + priceLabel.getWidth() + " " + authorsLabel.getWidth() + " " + titleLabel.getX()) ;
                                  m.put(book.getId(), new Integer(priceLabel.getWidth()  + authorsLabel.getWidth()));
					returnValue = renderer;
				}
                      			if(book.getTitle().equals("HTML 4 Bible")){
					titleLabel.setText(book.getTitle());
					authorsLabel.setText(book.getAuthors());
					priceLabel.setText("" + book.getPrice());

                   // priceLabel.addMouseListener(mtree);
                   // renderer.addMouseListener(mtree);
					if (selected) {
						renderer.setBackground(backgroundSelectionColor);
					} else {
						renderer.setBackground(backgroundNonSelectionColor);
					}
					renderer.setEnabled(tree.isEnabled());
                                 System.out.println(book.getId() + " " + priceLabel.getWidth() + " " + authorsLabel.getWidth() + " " + titleLabel.getX()) ;
                                        m.put(book.getId(), new Integer(priceLabel.getWidth()  + authorsLabel.getWidth()));
					returnValue = renderer;
				}

			}
		}
		if (returnValue == null) {
			returnValue = defaultRenderer.getTreeCellRendererComponent(tree,
					value, selected, expanded, leaf, row, hasFocus);
		}
		return returnValue;
	}
}

class NamedVector extends Vector {
	String name;

	public NamedVector(String name) {
		this.name = name;
	}

	public NamedVector(String name, Object elements[]) {
		this.name = name;
		for (int i = 0, n = elements.length; i < n; i++) {
			add(elements[i]);
		}
	}

	public String toString() {
		return "[" + name + "]";
	}
}

Open in new window



0
 
for_yanCommented:

The code above is full code - you cvan compile and try to select/deselect
any node.

This is excerpt which shows the piece which has to do with selection:

Here bollean selected keeps track if we are clicking first or second time
If at the time of clicking selected is false - the node will be slected
and boolean will become true;
next click will deselect and toggle slected to false

class MyJTree extends JTree implements MouseListener {
    HashMap m;
                     DefaultTreeSelectionModel sm = new DefaultTreeSelectionModel();
    boolean selected;
  public MyJTree(Vector v, HashMap m){
      super(v);
      this.addMouseListener(this);
      this.m = m;
               this.setSelectionModel(sm);

  }



public void mouseClicked(MouseEvent me) {

                  if(selected){ sm.clearSelection();
                      selected = false;
                  }
                        else
                  selected = true;

       TreePath tp = this.getPathForLocation(me.getX(), me.getY());
      System.out.println("x:" + me.getX() + "  y: " + me.getY());
      //  System.out.println(tp.toString());
     DefaultMutableTreeNode node = null;
    if(tp != null)
    node = (DefaultMutableTreeNode)
         tp.getLastPathComponent();
    else return;

   

               components.Book nodeInfo = null;
             if(node.getUserObject() instanceof components.Book)  {
       nodeInfo =  (components.Book)node.getUserObject();
      System.out.println(nodeInfo.getPrice());
                 if(m.get(nodeInfo.getId()) == null)return;
                 System.out.println((Integer)m.get(nodeInfo.getId()));
                      if (me.getX()-35 >  ((Integer)m.get(nodeInfo.getId())).intValue()){
                          System.out.println("button clicked");
                      }
             }


}
public void mousePressed(MouseEvent me) {

}

public void mouseExited(MouseEvent me) {}

public void mouseEntered(MouseEvent me) {}

    public void mouseReleased(MouseEvent me) {}


}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.