Получите String-текст из HTMLEditor и запишите его в файл - Javafx - PullRequest
1 голос
/ 23 марта 2020

Поэтому я попытался реализовать 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;
}
...