因此,我尝试实现HMTLEditor,添加了一个名为“保存文本”的按钮。我想获取在编辑器中键入的文本并将其保存到.txt文件。但是,当它“已保存”时,其中没有任何内容,那里什么也没有显示。有什么建议吗?
这是我的代码:
@Override
public void start(Stage stage) throws Exception {
// HTMLEditor
HTMLEditor htmleditor = new HTMLEditor();
stage.setTitle("HTMLEditor");
htmleditor.setPrefHeight(450);
htmleditor.setPrefWidth(800);
//adding css
Scene scene = new Scene(htmleditor);
scene.getStylesheets().add(getclass().getResource("htmleditor.css").toExternalForm());
stage.setScene(scene);
stage.show();
//Save button
Node node = htmleditor.lookup(".top-toolbar");
if (node instanceof ToolBar) {
ToolBar bar = (ToolBar) node;
Button saveButton = new Button("Save text");
bar.getItems().add(saveButton);
saveButton.setOnaction(new EventHandler<actionEvent>() {
@Override
public void handle(actionEvent event) {
String path = "OKAY2.txt";
String htmlText = htmleditor.getHtmlText();
try {
Files.write(Paths.get(path),removeHTML(htmlText).getBytes());
htmleditor.setHtmlText("Saving succeded!");
} catch (IOException e) {
htmleditor.setHtmlText("An error has accured: \n" + e.toString());
}
}
});
}
}
public static void main(String[] args) {
Application.launch(args);
}
public static String removeHTML(String input) {
int i = 0;
String[] str = input.split("");
String out = "";
boolean inTag = false;
for (i = input.indexOf("<"); i < input.indexOf(">"); i++) {
inTag = true;
}
if (!inTag) {
for (i = 0; i < str.length; i++) {
out+= str[i];
}
}
return out;
}