2

您好,我尝试使用Google Chart根据Java文件生成的一些数据来显示趋势线。这是我的部分代码

public void resolveEvolution() {
        this.evolution = new ArrayList<Long>();
        this.evolutionTime = new ArrayList<String>();
        Calendar first = Calendar.getInstance();
        first.setTime(this.start);
        first.set(Calendar.DAY_OF_MONTH, 1);
        Calendar last = Calendar.getInstance();
        last.setTime(this.end);

        int i = 0;

        this.dt = DataTable.create();
        dt.addColumn(ColumnType.NUMBER, "Time");
        dt.addColumn(ColumnType.NUMBER, "Utilisation");
        dt.addRow();
        while (first.before(last)) {
            Calendar endMonth = Calendar.getInstance();
            endMonth.setTime(first.getTime());
            endMonth.add(Calendar.MONTH, 1);
            endMonth.add(Calendar.DAY_OF_MONTH, -1);

            this.evolution
                    .add(actionQueries.countByComponent(this.selectedComponent,
                            first.getTime(), endMonth.getTime()));
            this.evolutionTime.add(first.get(Calendar.MONTH) + "/"
                    + first.get(Calendar.YEAR));
            dt.addRow();
            dt.setValue(i, 0, i);
            dt.setValue(i, 1,
                    actionQueries.countByComponent(this.selectedComponent,
                            first.getTime(), endMonth.getTime()));
            i++;
            first.add(Calendar.MONTH, 1);
        }
    }

    public DataTable getDt() {
        System.out.println(this.dt);
        return this.dt;
    }

这是我的xhtml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
    <head>    
<script type="text/javascript" src="https://www.google.com/jsapi"></script>    
<script type="text/javascript">      
    google.load("visualization", "1", {packages:["corechart"]});     
    google.setOnLoadCallback(drawChart);      
    function drawChart() {        
        var data = new google.visualization.DataTable();
        data = "#{globalComponentsManager.dt}";
        var options = {         
            title: 'Test',
                           trendlines: { 0: {} }

        };    
        var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));

        chart.draw(data, options);      
    }    
    </script> 
 </head>  
 <body>   
      <div id="chart_div" style="width: 900px; height: 500px;"></div> 
 </body> 

</html>

显然,它不起作用。那么如何将数据表从java传递给JavaScript呢?我正在使用JSF框架。谢谢。

4

1 回答 1

3

好吧,我终于找到了解决方案。我希望它可以帮助将来遇到同样困难的人。JSF 可以将一些参数从 Java 传递到 Web Page,包括 JSF 页面中的 JavaScript。所以我在 Java 文件中使用 StringBuilder 来构建 Rows 的字符串,例如 [[1,2],[5,9],[4,3]]。然后我将此字符串传递给 JavaScript,即谷歌图表的代码,如 data.addRows(#{stastics.rows})。对于谷歌图表代码的其他部分,只需参考谷歌图表文档。它运作良好,我终于得到了我需要的图表。

于 2013-08-27T08:05:27.260 回答