通过 JavaGD 创建 R 图像
File 1
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import org.rosuda.JRI.Rengine;
import org.rosuda.javaGD.GDCanvas;
public class TryR4 extends JFrame implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private Rengine engine;
public static GDCanvas gdc;
private JButton jbgo;
private int counter;
public TryR4()
{
super.setTitle("My R Plot");
super.setSize(600, 600);
// initialize GUI
jbgo = new JButton("Go");
gdc = new GDCanvas(600,600);
jbgo.addActionListener(this);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(jbgo,BorderLayout.PAGE_START);
this.getContentPane().add(gdc,BorderLayout.PAGE_END);
this.pack();
// initialize R
engine = new Rengine(new String[] {"--vanilla"}, false, null);
engine.eval(".setenv <- if (exists(\"Sys.setenv\")) Sys.setenv else Sys.putenv");
engine.eval(".setenv(\"JAVAGD_CLASS_NAME\"=\"TryR4Interface\")");
engine.eval("library(JavaGD)");
this.setVisible(true);
// initialize sth else
counter = 1;
}
public static void main(String args[])
{
new TryR4();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == jbgo)
{
engine.eval("JavaGD()");
engine.eval("a <- rnorm(100)");
engine.eval("plot(a,type=\"l\")");
gdc.initRefresh();
// save it to file
File f = new File("c:\\playaround\\play2.png");
BufferedImage buffImg = new BufferedImage(gdc.getWidth(), gdc.getHeight(),BufferedImage.TYPE_INT_RGB);
gdc.paintAll(buffImg.createGraphics());
try {
ImageIO.write(buffImg, "png", f);
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
this.setTitle("Random number (" + String.valueOf(counter) + ")");
counter ++;
}
}
}
File 2 - Interface
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.rosuda.javaGD.GDInterface;
public class TryR4Interface extends GDInterface {
public void gdOpen(double w, double h)
{
c = TryR4.gdc;
}
}