Newsgroup: it.comp.java
Titolo: JTree-icons





Vorrei avere icone diverse sulle foglie del mio 
albero, ma non riesco a visualizzarle. Uso il TreeCellRenderer  e non 
funziona. Qualcuno mi sa dire cosa sbaglio?


Grazie per l'aiuto


Francesca


 


Riporto il mio codice:


 


 


import java.awt.*;
import 
java.awt.event.*;
import javax.swing.*;
import 
javax.swing.event.*;
import javax.swing.tree.*;


 


public class F53ICO2 extends JApplet 

                          
implements KeyListener, TreeModelListener {
private JTree tree;
protected 
DefaultTreeModel treeModel;
    
DefaultMutableTreeNode 
component = 
   new 
DefaultMutableTreeNode("Radice");
 DefaultMutableTreeNode container = 

   new 
DefaultMutableTreeNode("Figlio1");
 DefaultMutableTreeNode box = 

   new 
DefaultMutableTreeNode("Figlio2");
 DefaultMutableTreeNode prova = 

   new DefaultMutableTreeNode("Nipote");


 


public void init() {
 


 


 component.add(container);
 component.add(box);
 box.add(prova);


 


 CellRenderer cell = new 
CellRenderer();
 


 


 tree = new 
JTree(component);
 tree.addKeyListener(this);
 tree.setCellRenderer(cell);


 


// treeModel = new 
DefaultTreeModel(component);
        

// treeModel.addTreeModelListener(new 
MyTreeModelListener());
 ((DefaultTreeModel)tree.getModel()).addTreeModelListener(this);
 
 getContentPane().add(tree);
}


 


 public void keyTyped(KeyEvent e) 
{
        if (e.getKeyCode() == 
KeyEvent.VK_F5) { 
      System.out.println("F5"); 

    
 }//if (e.getKeyCode() == KeyEvent.VK_F5) { 

    }


 


public void keyPressed(KeyEvent e) 
{
        if (e.getKeyCode() == 
KeyEvent.VK_F5) { 
  System.out.println("F5"); 


 


 }//if (e.getKeyCode() == KeyEvent.VK_F5) { 



 


    }


 


    /** Handle the key released 
event from the text field. */
    public void 
keyReleased(KeyEvent e) {
        if 
(e.getKeyCode() == KeyEvent.VK_F5) { 
  System.out.println("F5"); 



 


  DefaultMutableTreeNode fox = 

   new 
DefaultMutableTreeNode("Nipotino");
//  addObject(prova, fox, 
true);
  addObject(prova, "Nipotino", 
true);
 
 }//if (e.getKeyCode() == KeyEvent.VK_F5) { 



 


}


 


public void clear() 
{
       
component.removeAllChildren();
        
treeModel.reload();
    }


 


public DefaultMutableTreeNode addObject(DefaultMutableTreeNode 
parent,
//                                            
DefaultMutableTreeNode child,
      Object 
child,
                                            
boolean shouldBeVisible) {
 System.out.println("dentro a 
addobject");
 Integer numfigli = new 
Integer(parent.getChildCount());
// numfigli = 
parent.getChildCount();
 String numero = 
numfigli.toString();
 System.out.println("num figli " + 
numero);
 
        
DefaultMutableTreeNode childNode = 

                
new DefaultMutableTreeNode(child + 
numero);
 
        if (parent == 
null) {
            
parent = component;
        }


 


//        
treeModel.insertNodeInto(childNode, 
parent,parent.getChildCount());
 ((DefaultTreeModel)tree.getModel()).insertNodeInto(childNode, 
parent,parent.getChildCount());


 


        // Make sure the user can see 
the lovely new node.
        if 
(shouldBeVisible) 
{
            
tree.scrollPathToVisible(new 
TreePath(childNode.getPath()));
        
}
// treeModel.reload(component);
 ((DefaultTreeModel)tree.getModel()).reload();
        
return childNode;
 
    }
public void 
treeNodesChanged(TreeModelEvent e) {
 System.out.println("dentro a 
NodesChanged" + e);
        
}
        public void 
treeNodesInserted(TreeModelEvent e) {
 System.out.println("dentro a 
NodesInserted" + e);
 
        
}
 public void treeNodesRemoved(TreeModelEvent e) 
{
 System.out.println("dentro a NodesRemoved" + 
e);
        
}
        public void 
treeStructureChanged(TreeModelEvent e) {
 System.out.println("dentro a 
StructureChanged" + e);
        
}


 


private static class CellRenderer
      
implements TreeCellRenderer {


 


 private JLabel renderer;


 


 CellRenderer () {
  renderer = new 
JLabel();
  renderer.setOpaque (true);
    
 }//CellRenderer () {


 


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


 


      
  renderer.setIcon(new 
ImageIcon("excel.gif"));


 


  if (leaf) 
{
   renderer.setText(value.toString());
  } else 
{
   renderer.setText("ROOT: 
"+value.toString());
      
  }
  return renderer;
 }//public Component  
getTreeCellRendererComponent(JTree tree,
}//private static class 
CellRenderer


 


}    



DefaultMutableTreeNode("Radice");<BR>&nbsp;DefaultMutableTreeNode =
[per favore non postare in html]
ho provato il tuo programma e mi sembra che funzioni
*******************************************************************************
//<APPLET code="F53ICO2" width="200" height="200"></APPLET>



	public void init()
	{
		component.add(container);
		component.add(box);
		box.add(prova);




		getContentPane().add(tree);
	}

		}//if (e.getKeyCode() == KeyEvent.VK_F5) {
	}

		}//if (e.getKeyCode() == KeyEvent.VK_F5) {
	}


		}//if (e.getKeyCode() == KeyEvent.VK_F5) {
	}

	public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
	        Object child, boolean shouldBeVisible)
	{
		System.out.println("dentro a addobject");
		Integer numfigli = new Integer(parent.getChildCount());
		// numfigli = parent.getChildCount();
		String numero = numfigli.toString();
		System.out.println("num figli " + numero);
		DefaultMutableTreeNode childNode =
		        new DefaultMutableTreeNode(child + numero);
		if (parent == null)
		{
			parent = component;
		}
		        treeModel.insertNodeInto(childNode,
				parent, parent.getChildCount());
				        ((DefaultTreeModel) tree.getModel()).insertNodeInto(
				        childNode, parent, parent.getChildCount());
		// Make sure the user can see the lovely new node.
		if (shouldBeVisible)
		{
			tree.scrollPathToVisible(new TreePath(childNode.getPath()));
		}
		// treeModel.reload(component);
		((DefaultTreeModel) tree.getModel()).reload();
		return childNode;
	}
	public void treeNodesChanged(TreeModelEvent e)
	{
		System.out.println("dentro a NodesChanged" + e);
	}
	public void treeNodesInserted(TreeModelEvent e)
	{
		System.out.println("dentro a NodesInserted" + e);
	}
	public void treeNodesRemoved(TreeModelEvent e)
	{
		System.out.println("dentro a NodesRemoved" + e);
	}
	public void treeStructureChanged(TreeModelEvent e)
	{
		System.out.println("dentro a StructureChanged" + e);
	}
	private static class CellRenderer implements TreeCellRenderer
	{
		private JLabel renderer;
		CellRenderer ()
		{
			renderer = new JLabel();
			renderer.setOpaque (true);
		}
		public Component getTreeCellRendererComponent(JTree tree,
		        Object value, boolean selected, boolean expanded,
		        boolean leaf, int row, boolean hasFocus)
		{
			renderer.setIcon(new ImageIcon("icona.gif"));
			if (leaf)
			{
				renderer.setText(value.toString());
			}
			else
			{
				renderer.setText("ROOT: "+value.toString());
			}
			return renderer;
		}//public Component  getTreeCellRendererComponent(JTree tree,
	}//private static class CellRenderer
}
*****************************************************************************************
ciao_O
http://digilander.iol.it/schiele





Funziona, ma non vengono visualizzate le icone! Ho 
però provato in un altro modo: utilizzando la classe


 


class CustomRenderer extends 
DefaultTreeCellRenderer{
 Icon ico_ex = new 
ImageIcon("excel.gif");
 Icon ico_wd = new 
ImageIcon("word.gif");
 Icon ico_ac = new 
ImageIcon("acrobat1.gif");
 public CustomRenderer(){ 
 }// 
public CustomRenderer(){ 
 public Component 
getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean 
expanded, boolean leaf, int row, boolean hasFocus){ 
  Component 
result = super.getTreeCellRendererComponent(tree, value, selected, expanded, 
leaf, row, hasFocus);
  System.out.println("dentro a metodo di 
Customrenderer");
  TEMP = (DefaultMutableTreeNode) 
value;
  TEMPOR = (nodo)TEMP.getUserObject(); 

  String tipo_icon = 
TEMPOR.getFormato();
  
  if 
(tipo_icon.equals("XLS"))  
{
   setLeafIcon(ico_ex);
  }// if 
(tipo_icon.equals("XLS")  {
  else 
{
   if  (tipo_icon.equals("DOC"))  
{
    setLeafIcon(ico_wd);
   }// 
if  (tipo_icon.equals("DOC"))  {
   else 
{
    setLeafIcon(ico_ac);
   }// else 
di if  (tipoicon.equals("DOC"))  {
  }// else di if 
(tipo_icon.equals("XLS")  {
  return result; 

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


 


}//class CustomRenderer extends 
DefaultTreeCellRenderer{


 


 


che viene richiamata nel programma:


 


CustomRenderer customRenderer = new 
CustomRenderer(); 
 
jt.setCellRenderer(customRenderer);


 


dove jt è l'albero.


Dovrebbe funzionare, il problema è che quando 
l'applet gira entra in eccezione:


 


//per selezionare nodo con tasto 
destro
   int selectedRow = 
jt.getRowForLocation(e.getX(),e.getY());
   ((JTree)e.getComponent()).setSelectionRow(selectedRow);
   System.out.println("MSGDBG 
costruito forzatura");
   try  
{
    selectedPath = 
jt.getPathForLocation(e.getX(),e.getY());
    selectedNode 
= (DefaultMutableTreeNode) 
selectedPath.getLastPathComponent();
    System.out.println("MSGDBG 
costruito path");
   }
   catch (Exception 
ex) {     
    selectedPath =null; 

    System.out.println("MSGDBG Non sono sul nodo" 
);
    System.out.println("eccezione: " + 
ex);


 


   }


anche se clicco sul nodo: può la nuova classe 
interferire in qualche modo con la definizione del path dell'albero? Il testo 
aggiunto è corretto?


<DIV><EM></EM>&nbsp;</DIV>
ho provato a guardare il tuo sorgente ma alla fine ho ceduto...
ti prego di configurare il tuo programma delle news in modo
da non spedire messaggi in html
comunque tornando al listato del messaggio precedente ti ripeto 
che a me funziona (con l'appletviewer), mi appaiono le icone ;)
nel sorgente che ti ho riportato nel mio post uso una gif
di nome icona.gif che metto nella directory dell'applet
sei sicura di non aver sbagliato a nominare i file?
se ti viene generata un'eccezione e' meglio se 
scrivi di che eccezione si tratta
ciao_@
http://digilander.iol.it/schiele

SCUSA, RIMANDO IL MIO MESS:
Funziona, ma non vengono visualizzate le icone! Ho però provato in un altro
modo: utilizzando la classe
class CustomRenderer extends DefaultTreeCellRenderer{
 Icon ico_ex = new ImageIcon("excel.gif");
 Icon ico_wd = new ImageIcon("word.gif");
 Icon ico_ac = new ImageIcon("acrobat1.gif");
 public CustomRenderer(){
 }// public CustomRenderer(){
 public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row, boolean
hasFocus){
  Component result = super.getTreeCellRendererComponent(tree, value,
selected, expanded, leaf, row, hasFocus);
  System.out.println("dentro a metodo di Customrenderer");
  TEMP = (DefaultMutableTreeNode) value;
  TEMPOR = (nodo)TEMP.getUserObject();
  String tipo_icon = TEMPOR.getFormato();
  if (tipo_icon.equals("XLS"))  {
   setLeafIcon(ico_ex);
  }// if (tipo_icon.equals("XLS")  {
  else {
   if  (tipo_icon.equals("DOC"))  {
    setLeafIcon(ico_wd);
   }// if  (tipo_icon.equals("DOC"))  {
   else {
    setLeafIcon(ico_ac);
   }// else di if  (tipoicon.equals("DOC"))  {
  }// else di if (tipo_icon.equals("XLS")  {
  return result;
 }//public Component getTreeCellRendererComponent(JTree tree, Object value,

}//class CustomRenderer extends DefaultTreeCellRenderer{




   }

L'ECCEZIONE CHE SI PRESENTA QUANDO CLICCO SUL NODO è:
dentro a metodo di Customrenderer
dentro a metodo di Customrenderer
Exception occurred during event dispatching:
java.lang.NullPointerException
 at Swing$CustomRenderer.getTreeCellRendererComponent(Swing.java, Compiled
Code)
 at
javax.swing.plaf.basic.BasicTreeUI$NodeDimensionsHandler.getNodeDimensions(U
nknown Source)
 at javax.swing.tree.AbstractLayoutCache.getNodeDimensions(Unknown Source)
 at
javax.swing.tree.VariableHeightLayoutCache$TreeStateNode.updatePreferredSize
(Unknown Source)
 at javax.swing.tree.VariableHeightLayoutCache$TreeStateNode.expand(Unknown
Source)
 at javax.swing.tree.VariableHeightLayoutCache$TreeStateNode.expand(Unknown
Source)
 at javax.swing.tree.VariableHeightLayoutCache.ensurePathIsExpanded(Unknown
Source)
 at javax.swing.tree.VariableHeightLayoutCache.setExpandedState(Unknown
Source)
 at javax.swing.plaf.basic.BasicTreeUI.updateExpandedDescendants(Unknown
Source)
 at
javax.swing.plaf.basic.BasicTreeUI$TreeExpansionHandler.treeExpanded(Unknown
Source)
 at javax.swing.JTree.fireTreeExpanded(Unknown Source)
 at javax.swing.JTree.setExpandedState(Unknown Source)
 at javax.swing.JTree.expandPath(Unknown Source)
 at javax.swing.plaf.basic.BasicTreeUI.toggleExpandState(Unknown Source)
 at javax.swing.plaf.basic.BasicTreeUI.handleExpandControlClick(Unknown
Source)
 at javax.swing.plaf.basic.BasicTreeUI.checkForClickInExpandControl(Unknown
Source)
 at javax.swing.plaf.basic.BasicTreeUI$MouseHandler.mousePressed(Unknown
Source)
 at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
 at java.awt.Component.processMouseEvent(Unknown Source)
 at java.awt.Component.processEvent(Unknown Source)
 at java.awt.Container.processEvent(Unknown Source)
 at java.awt.Component.dispatchEventImpl(Unknown Source)
 at java.awt.Container.dispatchEventImpl(Unknown Source)
 at java.awt.Component.dispatchEvent(Unknown Source)
 at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
 at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
 at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
 at java.awt.Container.dispatchEventImpl(Unknown Source)
 at java.awt.Component.dispatchEvent(Unknown Source)
 at java.awt.EventQueue.dispatchEvent(Unknown Source)
 at java.awt.EventDispatchThread.pumpOneEventForComponent(Unknown Source)
 at java.awt.EventDispatchThread.pumpEventsForComponent(Unknown Source)
 at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
 at java.awt.EventDispatchThread.run(Unknown Source)
MSGDBG Dentro a Mouse Listener
-- 
Posted from 
smtp1.libero.it
 [193.70.192.51] 
via Mailgate.ORG Server - 
http://www.Mailgate.ORG

MSGDBG Dentro a Mouse Listener
mmmh...
per capire dove si origina l'eccezione dovrei vedere l'intero codice... 
comunque, anche se non so esattamente cosa che stai facendo
ho scritto un mio esempio prendendo spunto dal tuo codice
in particolare guarda come ho scritto la classe CustomTreeCellRenderer
(sono andato a curiosare nei sorgenti della Sun)
con il codice che ho scritto e' possibile avere un'icona diversa per ogni foglia
(l'icona viene passata al costruttore della classe CustomMutableTreeNode)
ciao_O
//<APPLET code="DemoTree" width="400" height="400"></APPLET>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
public class DemoTree extends JApplet implements KeyListener, MouseListener, TreeModelListener
{
	private JTree tree;
	private DefaultTreeModel treemodel;
	private CustomTreeCellRenderer treerenderer;
	private CustomMutableTreeNode radice =
	        new CustomMutableTreeNode("radice",null);
	private CustomMutableTreeNode nodoA =
	        new CustomMutableTreeNode("nodo A",null);
	private CustomMutableTreeNode nodoB =
	        new CustomMutableTreeNode("nodo B",null);
	private CustomMutableTreeNode nodoC =
	        new CustomMutableTreeNode("nodo C",new ImageIcon("home.gif"));
	public void init()
	{
		radice.add(nodoA);
		radice.add(nodoB);
		nodoB.add(nodoC);
		treerenderer = new CustomTreeCellRenderer();
 
		treemodel = new DefaultTreeModel(radice);
		tree = new JTree(treemodel);
		tree.addKeyListener(this);
		tree.addMouseListener(this);
		treemodel.addTreeModelListener(this);
		tree.setCellRenderer(treerenderer);
		getContentPane().add(tree);
	}
	public void keyTyped(KeyEvent e)
	{
	}
	public void keyPressed(KeyEvent e)
	{
	}
	public void keyReleased(KeyEvent e)
	{
		if (e.getKeyCode() == KeyEvent.VK_F5)
		{
			aggiungiNodo(nodoA, "nodo",true);
		}
		if (e.getKeyCode() == KeyEvent.VK_F1)
		{
			treerenderer.setLeafIcon(new ImageIcon("home.gif"));
 
			treemodel.reload();
		}
	}
	public void mouseClicked(MouseEvent e)
	{
	}
	public void mousePressed(MouseEvent e)
	{
		if (e.getModifiers() == InputEvent.BUTTON1_MASK)
		{
			if (e.getComponent() == tree)
			{
				TreePath path = tree.getPathForLocation(e.getX(), e.getY());
				if (path != null)
				{
					System.out.println(path);
//					TreeNode node =
//		(DefaultMutableTreeNode) path.getLastPathComponent();
//					System.out.println(node);
				}
			}
		}
	}
	public void mouseReleased(MouseEvent e)
	{
	}
	public void mouseEntered(MouseEvent e)
	{
	}
	public void mouseExited(MouseEvent e)
	{
	}
	public DefaultMutableTreeNode aggiungiNodo(
	       CustomMutableTreeNode parent, String child, boolean visible)
	{
		if (parent == null)
		{
			parent = radice;
		}
		DefaultMutableTreeNode node = 
		      new DefaultMutableTreeNode(child + parent.getChildCount());
		treemodel.insertNodeInto(node, parent, parent.getChildCount());
		if (visible)
		{
			tree.makeVisible(new TreePath(node.getPath()));
		}
		return (node);
	}
	public void treeNodesChanged(TreeModelEvent e)
	{
		System.out.println(e);
	}
	public void treeNodesInserted(TreeModelEvent e)
	{
		System.out.println(e);
	}
	public void treeNodesRemoved(TreeModelEvent e)
	{
		System.out.println(e);
	}
	public void treeStructureChanged(TreeModelEvent e)
	{
		System.out.println(e);
	}
	private class CustomMutableTreeNode extends DefaultMutableTreeNode
	{
		private Icon icon;
		public CustomMutableTreeNode(Object o, Icon i)
		{
			super(o);
			icon = i;
		}
		public Icon getIcon()
		{
			return (icon);
		}
	}
	public class CustomTreeCellRenderer extends DefaultTreeCellRenderer
	{
		public CustomTreeCellRenderer()
		{
		}
		public Component getTreeCellRendererComponent(JTree tree,
		        Object value, boolean selected, boolean expanded,
		        boolean leaf, int row, boolean hasFocus)
		{
			String stringValue =
	        tree.convertValueToText(value, selected, expanded, leaf, row, hasFocus);
			this.hasFocus = hasFocus;
			setText(stringValue);
			if (selected)
			{
				setForeground(getTextSelectionColor());
			}
			else
			{
				setForeground(getTextNonSelectionColor());
			}
			if (!tree.isEnabled())
			{
				setEnabled(false);
				if (leaf)
				{
					setDisabledIcon(getLeafIcon());
				}
				else if (expanded)
				{
					setDisabledIcon(getOpenIcon());
				}
				else
				{
					setDisabledIcon(getClosedIcon());
				}
			}
			else
			{
				setEnabled(true);
				Icon i = null;
 
				if (value instanceof CustomMutableTreeNode)
				{
					i = ((CustomMutableTreeNode) value).getIcon();
				}
				if (i != null)
				{
					setIcon(i);
				}
				else if (leaf)
				{
					setIcon(getLeafIcon());
				}
				else if (expanded)
				{
					setIcon(getOpenIcon());
				}
				else
				{
					setIcon(getClosedIcon());
				}
			}
			setComponentOrientation(tree.getComponentOrientation());
			this.selected = selected;
			return (this);
		}
	}
}
http://digilander.iol.it/schiele