Skip to content

Instantly share code, notes, and snippets.

@hogmoru
Created June 10, 2017 00:53
Show Gist options
  • Save hogmoru/aa25951d69c1c93327ada6ebe9a298d7 to your computer and use it in GitHub Desktop.
Save hogmoru/aa25951d69c1c93327ada6ebe9a298d7 to your computer and use it in GitHub Desktop.
import jdk.jshell.tool.JavaShellToolBuilder;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class REPL {
public static void main(String[] args) throws Exception {
REPL repl = new REPL();
SwingUtilities.invokeLater(repl::openFrame);
}
private BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10000);
private JTextField input ;
private JTextArea output ;
private InputStream inStream = new InputStream() {
@Override
public int read() throws IOException {
try {
return queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
return -1;
}
}
};
private OutputStream outStream = new OutputStream() {
@Override
public void write(byte[] b) throws IOException {
output.append(new String(b, StandardCharsets.UTF_8));
}
@Override
public void write(int b) throws IOException {
output.append(String.valueOf((char)b));
}
};
private void openFrame() {
JFrame f = new JFrame("REPL");
JPanel root = new JPanel(new BorderLayout());
f.getContentPane().add(root);
input = new JTextField();
output = new JTextArea();
output.setFont(Font.decode("monospaced"));
root.add(new JScrollPane(output), BorderLayout.CENTER);
root.add(input, BorderLayout.SOUTH);
input.addActionListener(this::evaluateInput);
Runnable shellRunnable = () -> {
try {
JavaShellToolBuilder.builder().in(inStream, null).out(new PrintStream(outStream)).run();
} catch (Exception e) {
e.printStackTrace();
}
};
new Thread(shellRunnable).start();
f.setSize(400, 300);
f.setVisible(true);
}
private void evaluateInput(ActionEvent event) {
input.getText().chars().forEachOrdered(queue::add);
queue.add((int)'\n');
input.setText("");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment