我有一个场景,我需要显示图表(使用jfreecharts生成)将其转换为png图像,然后使用servlet显示它们。
当图表代码扩展ApplicationFrame或Jframe时,当我使用servlet显示它时,我看到以下异常:
java.awt.HeadlessException: No X11 DISPLAY variable was set, but this program performed an operation which requires it. at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:159) at java.awt.Window.(Window.java:317) at java.awt.Frame.(Frame.java:419) at javax.swing.JFrame.(JFrame.java:194)
我通读了几个地方,这似乎是因为ApplicationFrame和JFrame会导致此错误。
如果我只传递图表对象,则会抛出
java.lang.IllegalArgumentException: Null 'chart' argument. org.jfree.chart.ChartUtilities.writeChartAsPNG(ChartUtilities.java:181) org.jfree.chart.ChartUtilities.writeChartAsPNG(ChartUtilities.java:136)
有没有解决方案?
答案 0 :(得分:1)
ChartUtilities
是正确的选择;也支持流。一种方法需要Using Headless Mode in the Java SE Platform,但我也让它与VNC合作。
附录:这是一个相关的论坛thread。
答案 1 :(得分:1)
我将以简单的方式向您解释,因为我遇到的问题与我新的一样。
步骤
DONE:
以下示例
package polo;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
/**
* Servlet implementation class PieChartDemo1Serv
*/
public class PieServ extends HttpServlet implements useme {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public PieServ() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("image/png");
ServletOutputStream out = response.getOutputStream();
DefaultPieDataset pieDataset = new DefaultPieDataset();
pieDataset.setValue("In-Network ", .80);
pieDataset.setValue("Out-of-Network ", .20);
JFreeChart chart = ChartFactory.createPieChart("", pieDataset, true, true, false);
ChartUtilities.writeChartAsPNG(out, chart, 202, 182);
System.out.println("done23");
}
}
现在我知道你还有什么。学习Pieplots / Legends来设置边框和格式。你可以做更多的事情。