JavaFX如何保存带有标签的文件?

问题描述 投票:1回答:1

我有一个带有TextArea的选项卡式编辑器,我想保存所选文件的textarea内容。

但是我该怎么做?

在这里,我定义了我的商品(或用英语定义的东西。我是丹麦人::

public static TabPane pane = new TabPane();
public static TextArea area;
public static ListView lines;
public static VBox box;
public static Tab tabs;
public static BorderPane bps;

我添加标签的代码:

public static void AddTab(String title, String con) {
    area = new TextArea();
    lines = new ListView();

    box = new VBox();
    bps = new BorderPane();
    bps.setLeft(lines);
    bps.setRight(area);
    box.getChildren().addAll(bps);

    tabs = new Tab(title);
    tabs.setContent(box);
    pane.getTabs().add(tabs);
}

当我添加标签时,我使用此代码:

int i;
for (i = 0; i < GUI.Editor.pane.getTabs().size(); i++) {

}

String title = "New File (" + i + ")";
GUI.Editor.AddTab(title, null);

GUI.Editor.pane.getSelectionModel().select(i);

但是如何以这种方式保存文件?。

哦,当然我知道我需要一个文件对话框(并且我已尝试保存文件)。

我唯一需要的是如何从选定的选项卡中获取内容(当我的意思是内容时,我是指TextArea的内容)。

select tabs save javafx-8
1个回答
0
投票

当您设置选项卡内容为VBox时,直接获取TextArea有点困难。一种方法是通过从VBox到Textarea进行多种类型转换,我们可以获得选定的区域。

private static TextArea getSelectedTabContent() {
        Node selectedTabContent = pane.getSelectionModel().getSelectedItem().getContent();
        if(selectedTabContent instanceof VBox){
            Node borderPane =  ((VBox) selectedTabContent).getChildren().get(0);
            if(borderPane instanceof BorderPane){
                Node textAreaNode = ((BorderPane) borderPane).getRight();
                if(textAreaNode instanceof  TextArea){
                    return (TextArea) textAreaNode;
                }
            }
        }
        return null;
    }

下面是要保存到文件的完整代码。

package com.pw.jnotepad.app;

import com.pw.jnotepad.app.providers.AlertBox;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;

public class StackOverflowAnswer extends Application {
    public static TabPane pane = new TabPane();
    public static TextArea area;
    public static ListView lines;
    public static VBox box;
    public static Tab tabs;
    public static BorderPane bps;
    public static Stage window;

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        area = new TextArea();
        lines = new ListView();

        box = new VBox();
        bps = new BorderPane();
        bps.setTop(createMenuBar());
        bps.setLeft(lines);
        bps.setRight(area);
        box.getChildren().addAll(bps);

        tabs = new Tab("tab-1");
        tabs.setContent(box);
        pane.getTabs().add(tabs);


        Scene scene = new Scene(pane);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    // to create menu bar with file menu
    private static MenuBar createMenuBar(){
        Menu fileMenu = new Menu("File");
        MenuItem saveFile = new MenuItem("Save");
        saveFile.setOnAction(event -> {
            System.out.println("Save file action triggered");
            FileChooser fileChooser = createFileChooser("Save File");
            File selectedFile = fileChooser.showSaveDialog(window);
            if(selectedFile != null){
                File savedFile =  saveTextToFile(selectedFile);
                if(savedFile!= null){
                    System.out.println("file saved successfully");
                    updateTabTitle(savedFile.getName());
                }
            }


        });
        fileMenu.getItems().addAll(saveFile);
        return new MenuBar(fileMenu);
    }

    // to open save dialog window
    private static FileChooser createFileChooser(String title) {
        FileChooser fileChooser = new FileChooser();
        FileChooser.ExtensionFilter onlyTextFilesFilter = new FileChooser.ExtensionFilter("Txt files(*.txt)", "*.txt");
        fileChooser.getExtensionFilters().add(onlyTextFilesFilter);
        fileChooser.setTitle(title);
        fileChooser.setInitialDirectory(Paths.get("").toAbsolutePath().toFile());
        return fileChooser;
    }
   // to save the file into disk
    public static File saveTextToFile(File file) {
            TextArea selectedTabContent = getSelectedTabContent();
            if(selectedTabContent!=null){
                try(BufferedWriter buffer = new BufferedWriter(new FileWriter(file));) {
                    ObservableList<CharSequence> paragraphs =  selectedTabContent.getParagraphs();
                    paragraphs.forEach(charSequence -> {
                        try {
                            buffer.append(charSequence);
                            buffer.newLine();
                        } catch (IOException e) {
                            System.out.println("failed to write to text file.");
                            AlertBox.display("File Save Error", "failed to write to text file.");
                            e.printStackTrace();
                        }
                    });
                    buffer.flush();
                    return file;
                } catch (IOException e) {
                    System.out.println("failed to write to text file.");
                    AlertBox.display("File Save Error", "failed to write to text file.");
                    e.printStackTrace();
                }
            }
            return null;
        }
    // to get selected text area
    private static TextArea getSelectedTabContent() {
        Node selectedTabContent = pane.getSelectionModel().getSelectedItem().getContent();
        if(selectedTabContent instanceof VBox){
            Node borderPane =  ((VBox) selectedTabContent).getChildren().get(0);
            if(borderPane instanceof BorderPane){
                Node textAreaNode = ((BorderPane) borderPane).getRight();
                if(textAreaNode instanceof  TextArea){
                    return (TextArea) textAreaNode;
                }
            }
        }
        return null;
    }
    // to update tab title by saved file name
    private static void updateTabTitle(String name){
        pane.getSelectionModel().getSelectedItem().setText(name);
    }

}

© www.soinside.com 2019 - 2024. All rights reserved.