Skip to content

Instantly share code, notes, and snippets.

@pgtwitter
Created January 18, 2015 16:05
Show Gist options
  • Save pgtwitter/18d549f1e12e41275ed7 to your computer and use it in GitHub Desktop.
Save pgtwitter/18d549f1e12e41275ed7 to your computer and use it in GitHub Desktop.
package rJava;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.rosuda.JRI.REXP;
import org.rosuda.JRI.Rengine;
abstract class RBase extends JPanel implements Runnable {
protected Rengine _engine;
protected Thread _thread;
protected boolean _loopFlag = true;
private boolean _lockFlag = false;
private File _file;
public RBase() {
_engine = new Rengine(new String[] {
"--no-save"
}, false, null);
init();
_file = paintIMP();
}
abstract void init();
abstract void plot();
abstract void step();
protected REXP eval(String cmd) {
return _engine.eval(cmd);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (_file != null) {
try {
BufferedImage img = ImageIO.read(_file);
g.drawImage(img, 0, 0, this);
} catch (Exception e) {
e.printStackTrace();
_file.delete();
_file = null;
}
}
_lockFlag = false;
}
private File paintIMP() {
File file = null;
try {
file = File.createTempFile("plot", ".png");
file.deleteOnExit();
_engine.eval("png('" + file.getAbsolutePath() + "')");
plot();
_engine.eval("dev.off()");
return file;
} catch (Exception e) {
if (file != null) {
file.delete();
file = null;
}
return null;
}
}
protected void toggle() {
if (!(_thread != null && _thread.isAlive()))
start();
else
_loopFlag = false;
}
protected void start() {
if (_thread == null || !_thread.isAlive()) {
_thread = new Thread(this);
_loopFlag = true;
_thread.start();
}
}
protected void stop() {
_loopFlag = true;
}
protected void reset() {
_loopFlag = true;
init();
_file = paintIMP();
repaint();
}
protected void quit() {
stop();
if (_engine != null && _engine.isAlive())
_engine.end();
}
@Override
public void run() {
try {
while (_loopFlag) {
_lockFlag = true;
repaint();
do {
Thread.sleep(10);
} while (_lockFlag);
step();
_file = paintIMP();
}
} catch (Exception e) {
e.printStackTrace();
_engine.end();
}
}
public static void show(RBase p) {
System.out.println("R_HOME:" + System.getenv("R_HOME"));
System.out.println("java.library.path:"
+ System.getProperty("java.library.path"));
JFrame f = new JFrame();
f.getRootPane().setContentPane(p);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
p.quit();
System.exit(0);
}
});
f.setSize(480, 500);
f.setVisible(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment