[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Toggle JTree nodes

Posted on 2011-05-04
3
Medium Priority
?
569 Views
Last Modified: 2012-08-13
I want to unselect the a tree node , if we select/clicked on already a selected node. Is it possible to do this.
0
Comment
Question by:Computer07
  • 3
3 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 35688270
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
 
LVL 47

Expert Comment

by:for_yan
ID: 35688306

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
 
LVL 47

Accepted Solution

by:
for_yan earned 1000 total points
ID: 35688330
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

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses
Course of the Month18 days, 5 hours left to enroll

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question