You are viewing a plain text version of this content. The canonical link for it is here.
Posted to batik-users@xmlgraphics.apache.org by Torstein Hegbom <th...@sensewave.com> on 2004/04/04 11:29:10 UTC

Capturing mouse click-event for a given Element in the DOM-tree

I have been reading the mailing lists and collected some code from the mailing list, and have a question:
Below you will find some code that will write the id of the clicked element. From what I understand there should not be nessecary to add a event listener for each element, since the mouse-event are propagating through the element tree if one element is clicked. The code below shows only the body-element, not all the other element. How is it possible to get the element that really was clicked on?



//called when a svg-document is loaded
private void captureDOMEvent()
    {
      String svgid=svgCanvas.getSVGDocument().getRootElement().getId();
      EventTarget t = 
(EventTarget)(svgCanvas.getSVGDocument().getElementById(svgid));            
      EventListener onClick = new OnClickAction(svgCanvas);
      t.addEventListener("click", onClick, false);
    }



import org.w3c.dom.Element;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.apache.batik.swing.JSVGCanvas;
 
 public class OnClickAction implements EventListener, Runnable
     {
    Event evt;
    JSVGCanvas svgCanvas;
   
    public OnClickAction(JSVGCanvas svgCanvas)
    {
           this.svgCanvas=svgCanvas;
    }

    public void handleEvent(Event evt)
    {
        this.evt = evt;
           
        if (Thread.currentThread() ==
        
svgCanvas.getUpdateManager().getUpdateRunnableQueue().getThread()){        
       
        Element elt = (Element)(evt.getCurrentTarget());
        if (elt != null) {
                String svgid = elt.getAttribute("id");
                System.out.println("ID: "+svgid);
        }
        }         
        else {
        try {
            svgCanvas.getUpdateManager().
            getUpdateRunnableQueue().invokeLater (this);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        }
    }

        public void run()
    {
        handleEvent(evt);
        }   
  }

Thanks
Torstein