Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
Clear All
new posts

    #16
    Project lessons learned. How to hover in a chart the easy way,

    Thank you for the fixes. I will reincorporate the fixes using 4.1 best practices and add a list grid, and repost a sample.

    So far I have learned a lot. For other readers ...

    1) In general, create a data value formatter. Don't try to use add a hover handler with mouseout and mouse move handlers for events to the hover. It's too much work. . Use ValueFormatters instead.

    Here I display a label and the number of docs, the the highlighting still works.

    Code:
    chart.setDataValueFormatter(new ValueFormatter(){
    			// TODO Auto-generated method stub
    		public String format(Object value){
    			if (chart.getNearestDrawnValue()!=null){
    			
    			Record record = chart.getNearestDrawnValue().getRecord();
    		
    			return  "" + record.getAttribute("label") + " " +  
                        "- " + record.getAttribute("docs") + "" +  
                     //
                        "";
    			}
    			else return value.toString(); // no record just return the value
    			
    		}
        	   
    	});
    BTW: I'd love a legend formatter, but ...
    2) Modify the above with settings to improve the design.
    3) There is a shocking difference in 4.1 to 4.0
    4) FacetValueMaps (especially if isomorphic implements return a getDrawnValues(fvm)[] are an excellent way to query the chart's current data and synchronize a grid to an interactive facetchart.

    Thanks .... 4.1

    Comment


      #17
      Thanks for all the info and insight. Do you have a sample based upon 4.1 that a neophite could follow for using piecharts?

      Thank You Kindly.

      Comment


        #18
        The advice in this thread should be ignored. This user was making attempts to work around a single bug, long since corrected. Just use the Charting examples in the Showcase as a starting point.

        Comment


          #19
          Forum code 4.1d a nd on advice in forums

          Stone,
          Yes, it is not all correct. The correct code has to use 4.1d (which broke my visualbuilder in smartgwtpro).

          I will update the example to 4.1d with a filter on the associated grid.
          ----------------------------------------------------------------------
          Being newish to smartgwt also I am still learning. Advice isn't perfect.

          I find the following very useful in the client.

          In JSNI - I use console.log("your error"); for writing to the browser log calls
          In SMARTGWT I use SC.say(); and SC.LogWarn(); Take a close look at the SC utility classes.
          Also I use debugger; to break into the debugger in JSNI for chrome and firefox. (I periodically use "DEADBEEF" as a search string to find the generated code).


          For third party JSNI, I strongly read hint that anyone using smartgwt read this .... http://www.gwtproject.org/doc/latest...asicsJSNI.html
          In general, I find alert(); in JSNI and Window.alert(); in SmartGWT useful but too invasive in the debugging process. Especially avoid Window.alert(); as there is a Smartgwt class called Window that it collides with.

          The code below illustrates the learning process of integrating a third party (Carrot2 FoamTree) into smartgwt when you are unfamiliar. Practices will not be perfect in the code on the forum.

          Code:
          
          public class GFoamTree extends HTMLFlow {
          	private JavaScriptObject chart;
              private String localparentElement;
              private GFoamTree self;
              final private String deadbeef = "gfoamtree deadbeef";
              String thisclass;
              static int count=0;
              // Don't do this with smartgwt 
              //public static native void exportStaticMethod() /*-{
              //$wnd.gfoamtree_trigger =
              //   $entry(@my.package.foamtree.client.GFoamTree::gfoamtree_trigger(Ljava/lang/String;)(event));
           	// }-*/;
          	public GFoamTree(String elementId) {
          		// exportStaticMethod();
          		setElement(Document.get().createElement("div"));
          		setContents("<div id=\"foamtree\" style=\"width: 400; height: 400\">tree  here</div>");
          	
          		thisclass=	this.getID();
          
          		gfoamtree_trigger("");
          	}
          	
          
          	/*
          	public GFoamTree() {
          	setElement(Document.get().createElement("div"));
          	 setContents("<div id=\"foamtree\" style=\"width: 400; height: 400\">tree  here</div>");
          	}
          	public GFoamTree(Canvas canvaselementId) {
          		localparentElement = canvaselementId.getElement().getId();
          		setElement(Document.get().createElement("div"));
          		setContents("<div id=\"foamtree\" style=\"width: 400; height: 400\">tree  here</div>");
          	}
          	*/
          	public void setData(Record[] data, String labelProperty, String weightProperty) {
          		Map<String, Integer> items = new HashMap<String, Integer>();
          		JSONArray records = new JSONArray();
          		//labelProperty = "label";
          		for (int i = 0; i < data.length; i++) {
          			Record r = data[i];
          			int current = 0;
          			String label = r.getAttribute(labelProperty);
          			if (items.containsKey(label))
          				current = items.get(label);
          			SC.logWarn(r.getAttributeAsInt("docs")+" here ");
          		//	items.put(label, ++current);  changed 
          			items.put(label,r.getAttributeAsInt("docs"));
          		}
          		int i = 0;
          		for (Map.Entry<String, Integer> entry : items.entrySet()) {
          			JSONObject obj = new JSONObject();
          			obj.put("label", new JSONString(entry.getKey()));
          			 SC.logWarn(" there "+entry.getValue());
          			obj.put("weight", new JSONNumber(entry.getValue()));
          			records.set(i, obj);
          			i++;
          		}
          		
          		setChartData(records.getJavaScriptObject(), "foamtree",thisclass);
          	}
          	@Override
          	public String getInnerHTML() {
          		// TODO Auto-generated method stub
          		return super.getInnerHTML();
          	}
          	/*
          	@Override
          	public void setParentElement(Canvas parentElement)
          			throws IllegalStateException {
          		// TODO Auto-generated method stub
          		super.setParentElement(parentElement);
          		
          		
          	}
          	*/
          	public native void setChartData(JavaScriptObject records, String id,String thisclass) /*-{
          		  console.log(records);
          
          		  gfoamtree = $wnd.CarrotSearchFoamTree({
          		    // Identifier of the DOM element
          		    // into which to embed FoamTree
          		    'id': id,
          		 
          		    // Other options can be set during embedding
          		    // as well. Here we set the border width to 8
          		    //'borderWidth': 8,
          		 
          		    // Group selection listener
          		    onGroupSelectionChanged: function(info) {
          		    	// don't have this working yet
          		    	alert("fired"); 
          		    	/// $wnd.gfoamtree_trigger("this worked");
          		      //	debugger;
          		       // this.gfoamtree_trigger("group selection " + info.group);
          		        var returncode = @my.package.foamtree.client.GFoamTree::gfoamtree_trigger(Ljava/lang/String;)(info.group);
          		        alert("ended");
          		    		    },
          		    dataObject: { groups: records }
          		  });
          		  alert("hello in here");
          		  console.log("Foam Tree - set chart data completed"); 
          
          		
          
          	}-*/;
          
          	public static int gfoamtree_trigger(String event) {
          		// not there yet
          		Window.alert("DEADERBEEF"+"ER1");
          		if (count<1){
          		Window.alert("DEADERBEEF"+"ER2");
          		Logger.getLogger("Events").info("Event " + event + " triggered");
          		}
          		count++;
          		return count;
          	}
          }
          I don't apologize for the code as it is a learning process to select practices, but please don't assume forums have the correct practices. Advice should be given and corrected, as the correction improves the knowledge base (as in the wiki process). (notice that I call the static method with a count in the constructor so the javac optimization doesn't remove the code for gfoamtree_trigger(); as dead code. BTW: it should be count>0.

          Thanks. for reading ...
          Last edited by jlhoward1; 1 Nov 2013, 11:04.

          Comment


            #20
            The above code

            To Stone...
            The above code has a significant problem that is not addressed by me. I don't need to fix the issue, but you might in other code. The code is expecting that the parent element of foamtree is drawn and visible. This code expects show and then setdata to occur. I am thinking that calling this code should be placed in it's parent's ondrawn event.

            Thanks

            Comment


              #21
              Never use SC.say() for debugging, you will only see the last message of a series of messages passed to it, and the fact that you are popping up a modal dialog will interfere with many behaviors you might be trying to troubleshoot (for example, it moves focus, and will prevent the second click in a double-click series).

              Never use alert() or Window.alert() either for similar reasons.

              Generally, use SC.logWarn() from SGWT, and isc.Log.logWarn() from JSNI, both of which log to the Developer Console and to the Eclipse console (since all warning-level logs appear there as well).

              Using a single logging approach (as opposed to logging some things to console.log() and some via SC.logWarn()) will mean that all logs appear in one place in the right relative order.

              We also don't recommend that developers new to SGWT start learning JSNI. The vast majority of SmartGWT developers never use JSNI. You should have a very specific and unusual need in mind before going off to learn JSNI.

              Comment


                #22
                Thank you and here is my working but not perfect JSNI

                Thank you.... I still use say and alert at times. :(


                BTW. Here is the working GFoamTree,java JSNI code for smartgwt .... no promises as to correctness.

                Read the google gwt JSNI tutorial.


                GFOAMTREE.JAVA
                Code:
                 
                package your.package.foamtree.client;
                
                
                
                import java.util.HashMap;
                import java.util.Map;
                import java.util.logging.Logger;
                
                
                
                
                
                
                import com.google.gwt.core.client.JavaScriptObject;
                import com.google.gwt.dom.client.Document;
                import com.google.gwt.event.shared.HandlerRegistration;
                import com.google.gwt.event.shared.HasHandlers;
                import com.google.gwt.json.client.JSONArray;
                import com.google.gwt.json.client.JSONNumber;
                import com.google.gwt.json.client.JSONObject;
                import com.google.gwt.json.client.JSONString;
                import com.google.gwt.user.client.Window;
                import com.smartgwt.client.data.Record;
                import com.smartgwt.client.util.SC;
                import com.smartgwt.client.widgets.HTMLFlow;
                import com.smartgwt.client.widgets.grid.events.SelectionChangedHandler;
                import com.smartgwt.client.widgets.grid.events.SelectionEvent;
                
                public class GFoamTree extends HTMLFlow implements HasHandlers{
                	private JavaScriptObject chart;
                 //   public gfoamtreeHandler foamtreeHandler;
                    final public String deadbeef = "gfoamtree deadbeef";
                    static int count=0;
                    
                    
                
                	public GFoamTree(String elementId) {
                
                		setElement(Document.get().createElement("div"));
                		setContents("<div id=\"foamtree\" style=\"width: 450; height: 700\">tree  here</div>");
                		
                		
                	//	gfoamtree_trigger(""); // static call --- as an example only not used ... use the instance call
                            // force code generation - gwtc will remove gfoamtree_trigger2 if not called by java
                		if (count==0) {
                	      gfoamtree_trigger2(""); // instance call 
                		}
                	}
                	
                
                	public void setData(Record[] data, String labelProperty, String weightProperty) {
                	//	this.gfoamtree_trigger2("");
                		Map<String, Integer> items = new HashMap<String, Integer>();
                		JSONArray records = new JSONArray();
                		
                		for (int i = 0; i < data.length; i++) {
                			Record r = data[i];
                			int current = 0;
                			String label = r.getAttribute(labelProperty);
                			if (items.containsKey(label))
                				current = items.get(label);
                			SC.logWarn(r.getAttributeAsInt("docs")+" here ");
                			items.put(label,r.getAttributeAsInt("docs"));
                		}
                		int i = 0;
                		for (Map.Entry<String, Integer> entry : items.entrySet()) {
                			JSONObject obj = new JSONObject();
                			obj.put("label", new JSONString(entry.getKey()));
                		//	 SC.logWarn("  there "+entry.getValue());
                			obj.put("weight", new JSONNumber(entry.getValue()));
                			records.set(i, obj);
                			i++;
                		}
                		
                		setChartData(this,records.getJavaScriptObject(), "foamtree");
                	}
                	@Override
                	public String getInnerHTML() {
                		// TODO Auto-generated method stub
                		return super.getInnerHTML();
                	}
                
                
                	public native void setChartData(GFoamTree thisclass, JavaScriptObject records, String id) /*-{
                		  console.log(records);
                
                		  gfoamtree = $wnd.CarrotSearchFoamTree({
                		    // Identifier of the DOM element
                		    // into which to embed FoamTree
                		    'id': id,
                		 
                		    // Other options can be set during embedding
                		    // as well. Here we set the border width to 8
                		    //'borderWidth': 8,
                		 
                		    // Group selection listener
                		    onGroupSelectionChanged: function(info) {
                		    	// don't have this working for static --- it's here to document the another approach --- use the instance
                		    	console.log("fired"); 
                		
                		    	//debugger;
                		    	//static call removed
                		           //    var returncode = @your.package.foamtree.client.GFoamTree::gfoamtree_trigger(Ljava/lang/String;)(info.group);
                		          // note 'this' is CarrotSearchFoamTree not GFoamtree
                		       var myselectedgroup= this.get("selection").groups[0].label;
                		          // GFoamtree changes 'this' in the scope to it's context so 'this.' won't work... pass in a 'thisclass' reference instead
                		       var returncode2 = thisclass.@your.package.foamtree.client.GFoamTree::gfoamtree_trigger2(Ljava/lang/String;)(myselectedgroup);
                		
                		      //  alert("ended "+myselectedgroup); // remove this ... no alerts
                		      
                		    },
                		    dataObject: { groups: records }
                		  });
                	
                		  console.log("Foam Tree - set chart data completed"); 	
                
                	}-*/;
                
                	public static int gfoamtree_trigger(String event) {
                		// 
                	
                		if (count>0){
                	
                		
                		Logger.getLogger("Events").info("Event " + event + " triggered");
                		}
                		count++;
                		return 0;
                	}
                	public int gfoamtree_trigger2(String event) {
                		// use this instance call.... 	
                		if (count>0){
                	
                			SC.logInfo("before event");
                 
                	   fireEvent(new GFoamTreeReceivedEvent(event));
                
                		}
                		count++;
                		return 0;
                	}
                	
                	
                	public HandlerRegistration addGFoamTreeHandler(GFoamTreeHandler handler) {
                		SC.logInfo("Adding handler");
                		HandlerRegistration r = doAddHandler(handler, GFoamTreeReceivedEvent.TYPE);
                		return r;
                	}
                
                	
                }

                GFoamTreeHandler.java
                Code:
                /**
                 * 
                 */
                package your.package.foamtree.client;
                // Not needed imports.... 
                //import com.google.gwt.view.client.SelectionChangeEvent;
                // import com.google.gwt.view.client.SelectionChangeEvent.Handler;
                
                /**
                 * @author howardjos
                 *
                 */
                public class GFoamTreeHandler implements IGFoamTreeEventHandler {
                
                	/**
                	 * 
                	 */
                	public GFoamTreeHandler() {
                		// TODO Auto-generated constructor stub
                	}
                
                	@Override
                	public void onMessageReceived(GFoamTreeReceivedEvent event) {
                		// TODO Auto-generated method stub
                		
                		
                	}
                
                	
                
                }
                GFoamTreeReceivedEvent.java
                Code:
                /**
                 * 
                 */
                package your.package.foamtree.client;
                
                
                import com.google.gwt.event.shared.GwtEvent;
                
                public class GFoamTreeReceivedEvent  extends GwtEvent<GFoamTreeHandler> {
                
                	
                		    public static Type<GFoamTreeHandler> TYPE = new Type<GFoamTreeHandler>();
                
                		    private final String message;
                
                		    public GFoamTreeReceivedEvent(String message) {
                		        this.message = message;
                		    }
                
                		    @Override
                		    public Type<GFoamTreeHandler> getAssociatedType() {
                		        return TYPE;
                		    }
                
                		    @Override
                		    protected void dispatch(GFoamTreeHandler handler) {
                		        handler.onMessageReceived(this);
                		    }
                
                		    public String getMessage() {
                		        return message;
                		    }
                		
                	}
                IGFoamTreeEventHandler.java
                Code:
                package your.package.foamtree.client;
                import com.google.gwt.event.shared.EventHandler;
                
                
                	public interface IGFoamTreeEventHandler extends EventHandler {
                	    void onMessageReceived(GFoamTreeReceivedEvent event);
                	}
                Last edited by jlhoward1; 16 Apr 2014, 15:16.

                Comment


                  #23
                  And in the calling program... part 2

                  in the module onLoad();
                  GFoamTree gfoamtree = new GFoamTree(""); /// .... must be on "top"


                  in my callback

                  Code:
                  .... 
                  	if (tabset.getSelectedTabNumber() == 0) { // foamtree tab 
                  	gfoamtree.show();
                  				}
                  				;
                  
                  	gfoamtree.setData(clusterdata.duplicate(), "label", "docs"); 
                  ....
                  And the handler ....
                  Code:
                  gfoamtree.addGFoamTreeHandler(new GFoamTreeHandler() {
                  			@Override
                  			public void onMessageReceived(GFoamTreeReceivedEvent event) {
                  				// TODO Auto-generated method stub
                  				super.onMessageReceived(event);
                  				// Window.alert("message received" + event.getMessage());  // Window,alert("bad habit to use window alert use logWarn"); 
                  				Record gfoamclusterrecord = clusterdata.findAll("label",
                  						event.getMessage())[0];
                  				AdvancedCriteria adCriteria = new AdvancedCriteria("_id",
                  						OperatorId.IN_SET, gfoamclusterrecord
                  								.getAttributeAsStringArray("FilterIds"));
                  
                  				grid.setData(griddata.findAll(adCriteria));
                  				// Sample browser MVC debugging displays... can't use system.err
                  				// in the browser side
                  				grid.redraw();
                  				
                  			}
                  		});
                  Last edited by jlhoward1; 16 Apr 2014, 15:18.

                  Comment

                  Working...
                  X