I've been trying to learn the basics of Javascript, so this afternoon I put together a small JavaFX application that has a raw text area on the left, and an HTML rendering on the right:
public class Fifty extends Application {
private String filePath = null;
private TextArea text;
public void init() throws Exception {
super.init();
Parameters parameters = getParameters();
List<String> unnamedParams = parameters.getUnnamed();
if (unnamedParams.size() > 0) {
filePath = unnamedParams.get(0);
}
}
public void start(Stage stage) throws Exception {
SplitPane splitPane = new SplitPane();
text = new TextArea();
final WebView web = new WebView();
try {
text.setText(readFile(filePath, Charset.defaultCharset()));
web.getEngine().loadContent(text.getText());
} catch (Exception e) {
alertException(e);
}
text.setStyle("-fx-font-family: monospace");
text.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(final ObservableValue<? extends String> observable,
final String oldValue, final String newValue) {
web.getEngine().loadContent(text.getText());
}
});
splitPane.getItems().addAll(text, web);
Scene scene = new Scene(splitPane);
scene.setFill(Color.RED);
stage.setScene(scene);
stage.setTitle("eleven-fifty: because i'm bad at naming things");
stage.show();
}
public void stop() {
try {
saveFile(filePath, text.getText());
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("file not saved!");
}
}
static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
static void saveFile(String path, String text) throws Exception {
PrintWriter out = new PrintWriter(path);
out.print(text);
out.close();
}
static void alert(String title, String body) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle(title);
alert.setContentText(body);
alert.show();
}
static void alertException(Exception e) {
StackTraceElement[] trace = e.getStackTrace();
int i = 0;
StringBuilder traceRes = new StringBuilder();
traceRes.append(String.format("%s\n", e.toString()));
for (StackTraceElement element: trace) {
traceRes.append(String.format("%s\n", element.toString()));
if (++i > 10) break;
}
alert("Exception", traceRes.toString());
}
}
Finally, a script to automatically launch the .jar file:
java -jar eleven-fifty.jar %1
pause
How can this simple application be improved?