We help IT Professionals succeed at work.

How to know JButton Click event when JButton is rendered in JTree node.

Computer07
Computer07 asked
on
Medium Priority
1,627 Views
Last Modified: 2012-06-27
I am using Jbutton in a particular node of a tree.  I am not able to get the click event for the button that is added to particular node of the tree.  Any body can tell me how to get the click event for the JButton when used in JTree node.
Here is the code that i am using::

 
package components;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellRenderer;

public class BookTree {
	public static void main(String args[]) {
		JFrame frame = new JFrame("Book Tree");
		Book javaBooks[] = {
				new Book("Core Java 2 Fundamentals", "Cornell/Horstmann",
						42.99f),
						new Book("Taming Java Threads", "Holub", 34.95f),
						new Book("JavaServer  Pages", "Pekowsky", 39.95f) };
		Book htmlBooks[] = { new Book("Dynamic HTML", "Goodman", 39.95f),
				new Book("HTML 4 Bible", "Pfaffenberger/Gutzman", 49.99f) };
		Vector javaVector = new NamedVector("Java Books", javaBooks);
		Vector htmlVector = new NamedVector("HTML Books", htmlBooks);
		Object rootNodes[] = { javaVector, htmlVector };
		Vector rootVector = new NamedVector("Root", rootNodes);
		JTree tree = new JTree(rootVector);
		TreeCellRenderer renderer = new BookCellRenderer();
		
		tree.setCellRenderer(renderer);
		JScrollPane scrollPane = new JScrollPane(tree);
		frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
		frame.setSize(300, 300);
		frame.setVisible(true);
	}
}

class Book {
	String title;

	String authors;

	float price;

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

	public String getTitle() {
		return title;
	}

	public String getAuthors() {
		return authors;
	}

	public float getPrice() {
		return price;
	}
}

class BookCellRenderer implements TreeCellRenderer {
	JLabel titleLabel;

	JLabel authorsLabel;

	JButton priceLabel;

	JPanel renderer;

	DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer();

	Color backgroundSelectionColor;

	Color backgroundNonSelectionColor;

	public BookCellRenderer() {
		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());
					if (selected) {
						renderer.setBackground(backgroundSelectionColor);
					} else {
						renderer.setBackground(backgroundNonSelectionColor);
					}
					renderer.setEnabled(tree.isEnabled());
					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

Comment
Watch Question

Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
The button isn't actually added to the gui so you can't use an ActionListener

Author

Commented:
IS it possible to add button and the use listener.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
Awarded 2011
Awarded 2011

Commented:


This works for me - you can see it prints
price when you click at the book
(it will print error when you click first time at the tree to open it - but
that can be taken care of with some branch at
the beginning of the event handling)

But when you click at the book itself
it works OK.

package components;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
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 {
	public static void main(String args[]) {
		JFrame frame = new JFrame("Book Tree");
		Book javaBooks[] = {
				new Book("Core Java 2 Fundamentals", "Cornell/Horstmann",
						42.99f),
						new Book("Taming Java Threads", "Holub", 34.95f),
						new Book("JavaServer  Pages", "Pekowsky", 39.95f) };
		Book htmlBooks[] = { new Book("Dynamic HTML", "Goodman", 39.95f),
				new Book("HTML 4 Bible", "Pfaffenberger/Gutzman", 49.99f) };
		Vector javaVector = new NamedVector("Java Books", javaBooks);
		Vector htmlVector = new NamedVector("HTML Books", htmlBooks);
		Object rootNodes[] = { javaVector, htmlVector };
		Vector rootVector = new NamedVector("Root", rootNodes);
		MyJTree tree = new MyJTree(rootVector);
		TreeCellRenderer renderer = new BookCellRenderer();

		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 {

  public MyJTree(Vector v){
      super(v);
      this.addMouseListener(this);
  }



public void mouseClicked(MouseEvent me) {


       TreePath tp = this.getPathForLocation(me.getX(), me.getY());
        System.out.println(tp.toString());
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                          tp.getLastPathComponent();

       components.Book nodeInfo =  (components.Book)node.getUserObject();
      System.out.println(nodeInfo.getPrice());


}
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;

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

	public String getTitle() {
		return title;
	}

	public String getAuthors() {
		return authors;
	}

	public float getPrice() {
		return price;
	}
}

class BookCellRenderer implements TreeCellRenderer {
	JLabel titleLabel;

	JLabel authorsLabel;

	JButton priceLabel;

	JPanel renderer;

	DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer();

	Color backgroundSelectionColor;

	Color backgroundNonSelectionColor;

	public BookCellRenderer() {
		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());
					if (selected) {
						renderer.setBackground(backgroundSelectionColor);
					} else {
						renderer.setBackground(backgroundNonSelectionColor);
					}
					renderer.setEnabled(tree.isEnabled());
					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

Awarded 2011
Awarded 2011
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.