Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2011-04-27
6
Medium Priority
?
1,265 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

0
Comment
Question by:Computer07
  • 3
  • 2
6 Comments
 
LVL 92

Expert Comment

by:objects
ID: 35474156
0
 
LVL 92

Expert Comment

by:objects
ID: 35474164
The button isn't actually added to the gui so you can't use an ActionListener
0
 

Author Comment

by:Computer07
ID: 35474423
IS it possible to add button and the use listener.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 92

Expert Comment

by:objects
ID: 35475307
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35477425


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

0
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 35477826

The code below  does not throw any errors.

Well, it is true, that it responds to click on the whole book node,
not necessarily on the button, but for practical
purposes it is probably similar.


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.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 = 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());
             }


}
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

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
In this post we will learn different types of Android Layout and some basics of an Android App.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month21 days, 5 hours left to enroll

810 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