Created
March 16, 2015 15:59
-
-
Save pelenthium/056e1ed1931583792784 to your computer and use it in GitHub Desktop.
Sample JavaFX application for use Nashorn JavaScript Engine in jdk8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javafx.application.Application; | |
import javafx.scene.Scene; | |
import javafx.scene.control.Button; | |
import javafx.scene.control.TextArea; | |
import javafx.scene.layout.BorderPane; | |
import javafx.scene.layout.HBox; | |
import javafx.scene.layout.VBox; | |
import javafx.stage.Stage; | |
import jdk.nashorn.api.scripting.NashornScriptEngine; | |
import jdk.nashorn.api.scripting.NashornScriptEngineFactory; | |
import javax.script.ScriptException; | |
import java.io.PrintWriter; | |
import java.io.StringWriter; | |
public class Launcher extends Application { | |
TextArea textArea; | |
TextArea consoleTextArea; | |
@Override | |
public void start(Stage primaryStage) throws Exception { | |
BorderPane root = new BorderPane(); | |
Scene scene = new Scene(root); | |
textArea = new TextArea(); | |
consoleTextArea = new TextArea(); | |
consoleTextArea.setEditable(false); | |
Button runButton = new Button("Run"); | |
Button cleanButton = new Button("Clean console"); | |
cleanButton.setOnAction((e) -> { | |
consoleTextArea.clear(); | |
}); | |
runButton.setOnAction((e) -> { | |
NashornScriptEngine engine = (NashornScriptEngine) new NashornScriptEngineFactory().getScriptEngine(); | |
StringWriter writer = new StringWriter(); | |
engine.getContext().setWriter(writer); | |
try { | |
engine.eval(textArea.getText()); | |
} catch (ScriptException e1) { | |
e1.printStackTrace(new PrintWriter(writer)); | |
} | |
consoleTextArea.setText(writer.toString()); | |
}); | |
root.setCenter(textArea); | |
root.setBottom(new VBox(){{ | |
getChildren().addAll(new HBox(){{ | |
setSpacing(15); | |
getChildren().addAll(runButton, cleanButton); | |
}}, consoleTextArea); | |
}}); | |
primaryStage.setScene(scene); | |
primaryStage.setTitle("Nashorn JavaScript Engine"); | |
primaryStage.show(); | |
} | |
public static void main(String[] args) { | |
launch(args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment