pessoal, baixei a lib do chartCreator1.2.0 alguém poderia me dizer como utilizar esse cara com jsf???
ChartCreator
7 Respostas
bom seguinte
Eu trabalhei com Jfreechart e com jsf mas para isso tivemos que fazer um servlet que retorna para a pagina um array de bytes assim o jsf consegue criar o grafico na tela, sem precisar salvar em um diretorio, se vc for trabalhar so com o chartcreator ao criar o grafico vc tera que salvalo em um diretorio no servidor e seu aplicação chamaria a url desta imagem, mas fazendo assim fica muito ruim a aplicação…
então minha sujestão é que vc faça um metodo para gerar o array de bytes,“a imagem do grafico”, e seu servlet retorne para a aplicação este array…
public class ServletGrafico extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 7525881554438222L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String attribute = request.getParameter("attribute");
byte[] image = null;
image = (byte[]) request.getSession().getAttribute(attribute);
response.getOutputStream().write(image);
} catch (IOException e) {
e.printStackTrace();
}
}
}
la seu MB
vc cria o grafico normalmente so que vc tem que setar a imagem na sessao
ai vc faz assim
byte[] imagem = ChartUtilities.encodeAsPNG(chart.createBufferedImage(1000, 500));
setSessionValue("nomeDoMeuGrafico", imagem);
espero ter ajudado qq coisa pergunta ai…
abraço
cara muito interessante, mas ainda estou com duvidas quanto a tag da veiw como posso fazer para chamar o grafico ?
Poderia me mandar alguma coisa de exemplo disso?
Desculpe é que sou iniciante nisso, nunca ifz graficos com java e mesmo assim estou estudando apenas …
Aguardo então !
Abraços
:!:
Ei cara, tava com o mesmo problema seu, através do source e war que baixei do chartcreator, consegui estudar ele e descobrir como funciona, se precisar gero um zip e te envio. na verdade eu gostaria de usar o primefaces, como não consegui fazer funcionar, vou usar esse mesmo por em quanto.
um abraço.
sim pois é mas quem disse que JFreeChart não da para user com JSF???
Ontém eu consgui compilar um projeto e plotou o grafico sem problemas … !
Mais algumas horas e eu colocarei aqui no forum como eu fiz … esperem fque daqui pouco vou postar …
Falo t+
Fiz da seguinte maneira com um projeto já existente só adicionei os jar´s e fiz a configuração do JSF eis codigo:
package org.marx.hr.charting;
import de.laures.cewolf.DatasetProducer;
import de.laures.cewolf.tooltips.CategoryToolTipGenerator;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
/**
* More highly customized example than most of the other examples associated
* with the article "Visualize Your Oracle Database Data with JFreeChart."
*/
public class HrDeptSalariesCategoryDataset
implements DatasetProducer, CategoryToolTipGenerator, Serializable
{
HrDatabaseAccess dbAccess = new HrDatabaseAccess();
Map<Integer, List<HrEmployee>> departmentSalariesSeries = null;
Map<Integer, String> departmentIdToName = null;
public HrDeptSalariesCategoryDataset()
{
}
/**
* Not part of any of the interfaces that I implement - this is my own thing.
*/
private void setUpData()
{
departmentSalariesSeries = new HashMap<Integer, List<HrEmployee>>(); // dept id to list of salaries
List<HrEmployee> employees = dbAccess.getEmployees();
for ( HrEmployee employee : employees )
{
int departmentId = employee.getDepartmentId();
if ( departmentSalariesSeries.containsKey(departmentId) )
{
departmentSalariesSeries.get(departmentId).add(employee);
}
else // have not stored any salaries from this department yet
{
List<HrEmployee> employeesPerDepartment = new ArrayList<HrEmployee>();
employeesPerDepartment.add(employee);
departmentSalariesSeries.put(departmentId, employeesPerDepartment);
}
}
departmentIdToName = dbAccess.getDepartmentNameMapping();
}
/**
*
*
* @param aMap
*/
public Object produceDataset(Map aMap)
{
DefaultCategoryDataset categoryDataset = new DefaultCategoryDataset();
setUpData();
for ( Integer departmentId : departmentSalariesSeries.keySet() )
{
List<HrEmployee> employeesPerDepartment =
departmentSalariesSeries.get(departmentId);
for ( HrEmployee employee : employeesPerDepartment )
{
categoryDataset.addValue( employee.getSalary(),
employee.getFirstName() + " " + employee.getLastName(),
departmentIdToName.get(departmentId) );
}
}
return categoryDataset;
}
/**
* Not currently implemented - returns false.
*/
public boolean hasExpired(Map map, Date date)
{
return false;
}
/**
* Not currently implemented - returns null.
*/
public String getProducerId()
{
return null;
}
/**
* Not currently implemented - returns null.
*/
public String generateToolTip(CategoryDataset categoryDataset, int i, int i2)
{
return null;
}
/**
* This method unfortunately brings several JFreeChart dependencies into this
* class that were not otherwise required. However, it is worth that cost
* to make sure that the code works properly before hooking it up to its
* intended JSP client.
*
* @param aCategoryDataset CategoryDataset with data for chart generation.
*/
private static void createTestChart(CategoryDataset aCategoryDataset)
{
JFreeChart stackedBarChart = ChartFactory.createStackedBarChart(
"How Salaries Add Up Along Departments",
"Departments",
"Employees' Salaries",
aCategoryDataset,
PlotOrientation.VERTICAL,
true,
true,
true );
try
{
ChartUtilities.writeChartAsPNG( new FileOutputStream("C:\\dustinTest.png"),
stackedBarChart,
1200, 800 );
}
catch (IOException ioEx)
{
ioEx.printStackTrace();
}
}
/**
* Test driver.
*/
public static void main(String [] args)
{
HrDeptSalariesCategoryDataset me = new HrDeptSalariesCategoryDataset();
DefaultCategoryDataset dataset =
(DefaultCategoryDataset) me.produceDataset(new HashMap());
createTestChart(dataset);
}
}
agora eis a view:
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://richfaces.org/a4j" prefix="a4j" %>
<%@ taglib uri="http://richfaces.org/rich" prefix="rich" %>
<%@ taglib prefix="cewolf" uri="etc/cewolf.tld" %>
<jsp:useBean id="chartData" class="org.marx.hr.charting.HrDeptSalariesCategoryDataset"/>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Esperiência com Gráficos</title>
</head>
<body>
<f:view>
<h:form>
<h:outputText value="Esperiência com Gráficos"/><br /><br />
<cewolf:chart id="theChart" type="stackedverticalbar"
title="Salaries For Each Department"
xaxislabel="Departments" yaxislabel="Salaries">
<cewolf:data>
<cewolf:producer id="chartData" />
</cewolf:data>
</cewolf:chart>
<cewolf:img chartid="theChart" renderer="/cewolf" width="1200" height="800" />
</h:form>
</f:view>
</body>
</html>
bom eu não sei se isso demonstra que é assim, mas comigo deu certo…
johnibat manda para mim o arquivo zip e se precisar mando para vc também o sisteminha que peguei na net… manda para o arquivo zip !!!
Ei cara, tava com o mesmo problema seu, através do source e war que baixei do chartcreator, consegui estudar ele e descobrir como funciona, se precisar gero um zip e te envio. na verdade eu gostaria de usar o primefaces, como não consegui fazer funcionar, vou usar esse mesmo por em quanto.um abraço.
manda para mim o arquivo zip que vc falou aí se procisar mando para vc o que eu tenho … manda seu email e manda junto o arquivo zip do vc fez!
Por gente leza !?