0

Set Button Image via sclass in Java dynamically

asked 2012-10-09 19:41:23 +0800

ansancle gravatar image ansancle
317 9

updated 2012-10-09 19:45:44 +0800

I need to be able to specify the image for a button in Java at runtime. I don't have the path to the png but only have the sclass that defines the image.
If I do the following you get the correct image :
Java Code

Image image = new Image();
image.setSclass("imageSclass");

This image will correctly display whatever image is defined by the sclass.

If I have a button though, and I want the label to be below the image, and I try the following, it does not work since getContent returns null - I don't think the client has had a chance to resolve the sclass and load it. Setting the button Sclass only changes the entire button into basically the same thing as an image - you lose all the button styling and it only shows the image.

Java Code

Image image = new Image();
image.setSclass("imageSclass");

Button button = new Button();
button.setLabel("test");
button.setOrient("vertical");
button.setImageContent(image.getContent());

Does anyone know how I can set the button image via Sclass dynamically in the java code?

These components are being created in Java on the fly based on queries to the database, so they cannot be defined in the zul statically.

Thanks
-Andy

delete flag offensive retag edit

4 Replies

Sort by ยป oldest newest

answered 2012-10-10 07:35:37 +0800

psingh gravatar image psingh flag of India
963 8

@ansancle: Button is also creating dynamically or its is in zul file ?

link publish delete flag offensive edit

answered 2012-10-10 08:53:55 +0800

psingh gravatar image psingh flag of India
963 8

@ansancle : hope below code will workout for you but without sclass.

Button btnSave = new Button();
btnSave.setImage("/images/accept.gif");
btnSave.addEventListener("onClick", new EventListener<Event>() {

public void onEvent(Event arg0) throws Exception {

Messagebox.show("Hello! Welcome to the Wold");
}

});
grpID.appendChild(btnSave);

link publish delete flag offensive edit

answered 2012-10-10 10:54:12 +0800

ansancle gravatar image ansancle
317 9

thanks for the response.

However, the button is created dynamically and I don't have the image path - it does work properly when given an image path. I only have the sclass available.
Outside of parsing the stylesheet and getting the image path that way, I was hoping for a way via the sclass to create the image and set it into the button dynamically.

Image image = new Image();
image.setSclass("imageSclass");

Button button = new Button();
button.setLabel("test");
button.setOrient("vertical");
button.setImageContent(image.getContent());

link publish delete flag offensive edit

answered 2012-10-10 16:44:28 +0800

ansancle gravatar image ansancle
317 9

The way I solved this was to write code to read in the stylesheets from their URL and then load all sclass entries for images into a map that stores both the sclass and the imagepath.
I threw this together so there is DEFINITELY nicer ways of handling it, but wanted to post this for a reference to be used.
At a minimum it's a grunt stylesheet parser - a little work and this could be much nicer.

I have a main style sheet based upon device - one for desktop, one for Ipad, one for Iphone.
Inside that main stylesheet it uses the @import statement to include all the other stylesheets I use.

My utility runs at startup and first reads that first stylesheet, then get's all the nested stylesheets, and for each one of the those stores sclass's for any
image definitions inside the stylesheet. I can then at runtime ask for an imagepath from an sclass and use that to dynamically set the image on a button.

Inside zk.xml :

	<system-property>
	    <name>ipadStyleSheet</name>    
	    <value>/stylesheets/dhIpadStyleSheet.css</value>    
	</system-property> 
	<system-property>
	    <name>desktopStyleSheet</name>    
	    <value>/stylesheets/dhDesktopStyleSheet.css</value>    
	</system-property> 


Inside the dhIpadStyleSheet


@import "/dhuiipad/stylesheets/dhAudioStyleSheetIpad.css";
@import "/dhuiipad/stylesheets/dhNotificationsStyleSheetIpad.css";
@import "/dhuiipad/stylesheets/dhUserStyleSheetIpad.css";
@import "/dhuiipad/stylesheets/dhSystemStyleSheetIpad.css";
@import "/dhuiipad/stylesheets/dhHeaderStyleSheetIpad.css";
@import "/dhuiipad/stylesheets/dhAlertStyleSheetIpad.css"; 
@import "/dhuiipad/stylesheets/dhComponentsStyleSheetIpad.css"; 
@import "/dhuiipad/stylesheets/dhZoneIconsStyleSheetIpad.css";
@import "/dhuiipad/stylesheets/dhVideoStyleSheetIpad.css";  
@import "/dhuiipad/stylesheets/dhTextFontsStyleSheetIpad.css";


Here is the class that reads the parent, then all the imported stylesheets and maps the sclass to the paths :


/**
 * 
 */
package com.dh.ui.common.css;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

import org.apache.commons.io.IOUtils;


/**
 * @author ansancle
 *
 */
public class DHzCssImageMapper
{	
	private static Collection<DHzStyleEntryHolder> _sheetEntries = new ArrayList<DHzStyleEntryHolder>();
	private static Map<String,String> _cssImageMap = new HashMap<String,String>();
	
	
	/**
	 * 
	 * Method : getImagePathFromSclass
	 *
	 * @param sclass
	 * @return
	 */
	public String getImagePathFromSclass(String sclass)
	{
		String path = _cssImageMap.get(sclass);
		if (path == null)
			path = "";
		return path;
	}
	
	
	/**
	 * 
	 * Method : openAndLoadAllStyleSheetsFromParent
	 * 
	 *  this will load the root style sheet which lists all the other stylesheets.
	 *  It will then go through all of those and load the .dh styles into a map.
	 *
	 * @param zkSession
	 * 
	 */
	public static void openAndLoadAllStyleSheetsFromParent(String styleSheetUrl,String hostName,String styleSheet) throws Exception
	{
		// It's already loaded, no need to do it again.
		if (_cssImageMap.size() > 0)
			return;
		
		String parentSheetUrl = styleSheetUrl + styleSheet;
		
		
		URL url = new URL(parentSheetUrl);
		String rootSheetContents = IOUtils.toString(url.openStream());
		InputStream inputStream = IOUtils.toInputStream(rootSheetContents);
		BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));	
				
		// at this point we have a string containing all the the stylesheets defined in the parent style sheet
		// Ex. 
		// @import "/dhuiipad/stylesheets/dhAudioStyleSheetDesktop.css";
		// @import "/dhuiipad/stylesheets/dhNotificationsStyleSheetDesktop.css";
		
		Collection<String> cssFileUrls = new Vector<String>();
		
		 String line;
		 while ((line = br.readLine()) != null) 
		 {
			 int indexOfFirstSlash = line.indexOf("/");
			 line = line.substring(indexOfFirstSlash); // should be -> /dhuiipad/stylesheets/dhAudioStyleSheetDesktop.css";
			 int indexOfQuote = line.indexOf("\"");
			 line = line.substring(0,indexOfQuote); // should be -> /dhuiipad/stylesheets/dhAudioStyleSheetDesktop.css
			 String sheetUrl = "http://" + hostName + line;
			 cssFileUrls.add(sheetUrl);
		 }

		 Iterator<String> it = cssFileUrls.iterator();
		 while (it.hasNext())
		 {
			 String sheetName = it.next();
			 URL sheetUrl = new URL(sheetName);
			 String contents = IOUtils.toString(sheetUrl.openStream());
			 InputStream sheetInputStream = IOUtils.toInputStream(contents);
			 BufferedReader sheetInputBr = new BufferedReader(new InputStreamReader(sheetInputStream));	
			 while ((line = sheetInputBr.readLine()) != null) 
			 {
				 getCssEntry(line,sheetInputBr);
			 }
		 }
		 
		 
		 Iterator<DHzStyleEntryHolder> holderIts = _sheetEntries.iterator();
		 while (holderIts.hasNext())
		 {
			 DHzStyleEntryHolder holder = holderIts.next();
			 String imagePath = holder.getImagePath();
			 if (imagePath != null)
			 {
				 _cssImageMap.put(holder.getName(),imagePath);
				 System.out.println("Name = " + holder.getName() + " Path = " + imagePath);
			 }
		 }
		 
	}
	
	/**
	 * 
	 * Method : getCssEntryStart
	 *
	 * @param line
	 * @param br
	 * @throws Exception
	 */
	private static void getCssEntry(String line, BufferedReader br) throws Exception
	{
		// Get the next entry
		while ((line != null) && (line.contains(".dh") == false))
		{
			line = br.readLine();
		}
		// If we are here we have either got to the end of the file or we have found an entry
		if (line == null)
			return;
		
		DHzStyleEntryHolder entry = new DHzStyleEntryHolder();
		Collection<String> body = new ArrayList<String>();
		int indexofDot = line.indexOf(".");
		line = line.substring(indexofDot + 1);
		entry.setName(line);
		
		boolean bDone=false;
		
		while ((bDone == false) && (line != null))
		{
			line = br.readLine();
			body.add(line);
			if ((line.contains("}") == true))
			{
				bDone = true;
			}
		}
		// If we did not find the end brace but reached the end of the file we have an improprer entry in the style sheet.
		if ((bDone == false) && (line == null))
			throw new Exception("Did not find end of Style Entry before getting to end of file");
		
		entry.setBody(body);	
		_sheetEntries.add(entry);
	}

}

Here is the StyleEntry holder class

/**
 * Digital Home - Digital Health Systems Copyright 2005-2012
 * Date Created : Sep 22, 2011
 * Created By : ansancle
 * Package Name : com.dh.ui.common.css
 * File Name : DHzStyleEntryHolder.java
 *   
 *
 */
package com.dh.ui.common.css;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @author ansancle
 *
 */
public class DHzStyleEntryHolder implements Comparable<DHzStyleEntryHolder>
{	


	private String _name;
	private Collection<String> _body = new ArrayList<String>();
	private String _imagePath;
	
	/**
	 *  Method : compareTo
	 *
	 * (non-Javadoc)
	 * @see java.lang.Comparable#compareTo(java.lang.Object)
	 */
	@Override
	public int compareTo(DHzStyleEntryHolder object)
	{
		return _name.compareTo(object.getName());
	}
	
	/**
	 * 
	 * Method : setName
	 *
	 * @param name
	 */
	public void setName(String name)
	{
		_name = name;
	}
	
	/**
	 * 
	 * Method : getName
	 *
	 * @return
	 */
	public String getName()
	{
		return _name;
	}
	
	/**
	 * 
	 * Method : setBody
	 *
	 * @param body
	 */
	public void setBody(Collection<String> body)
	{
		_body = body;
	}
	
	/**
	 * 
	 * Method : getBody
	 *
	 * @return
	 */
	public Collection<String> getBody()
	{
		return _body;
	}
	
	/**
	 * 
	 * Method : getImagePath
	 *
	 *	Returns either imagePath or null if not an image entry
	 *
	 * @return
	 */
	public String getImagePath()
	{
		Iterator<String> it = _body.iterator();
		while (it.hasNext())
		{
			String line = it.next();
			if (line.contains("background: URL(") == true)
			{
				int index = line.indexOf(".");
				index = index + 1;
				line = line.substring(index);
				index = line.indexOf(")");
				line = line.substring(0,index);
				_imagePath = "/stylesheets" + line;
				return _imagePath;
			}
		}

		return null;
	}
	
	
}


And here is the code in the SessionInitListener where this get's called and loaded


	@Override
	public void init(Session session, Object request) throws Exception
	{
		
		javax.servlet.http.HttpServletRequest servletRequest = (javax.servlet.http.HttpServletRequest)request;
		String browserType = servletRequest.getHeader("User-Agent");		
		if ((browserType.indexOf(DHnSessionArguments.iPad.toString()) != -1) || (browserType.indexOf(DHnSessionArguments.iPhone.toString()) != -1))
	    {
			session.setAttribute(DHnSessionArguments.browserType.toString(), DHnPageArguments.iPad.toString());			
	    }	
		else
		{
			String remoteHostName = servletRequest.getRemoteHost();
			InetAddress inetAddress = InetAddress.getByName(remoteHostName);  
			String hostName = inetAddress.getHostName();	
			String styleSheet = DHzZKUtilities.getStyleSheetForBrowser(session, browserType);
			String styleSheetUrl = "http://" +  hostName + "/dhuiipad";
			// THIS CALL IS WHAT READS AND LOADS ALL THE STYLES into a static map - AFTER THIS CALL 
			// DHzCssImageMapper.getImagePathFromSclass(sclass) can be used to get an image Path
			DHzCssImageMapper.openAndLoadAllStyleSheetsFromParent(styleSheetUrl,hostName,styleSheet);
		}
	}

link publish delete flag offensive edit
Your reply
Please start posting your answer anonymously - your answer will be saved within the current session and published after you log in or create a new account. Please try to give a substantial answer, for discussions, please use comments and please do remember to vote (after you log in)!

[hide preview]

Question tools

Follow

RSS

Stats

Asked: 2012-10-09 19:41:23 +0800

Seen: 192 times

Last updated: Oct 10 '12

Support Options
  • Email Support
  • Training
  • Consulting
  • Outsourcing
Learn More