How to read RTF file and display in JavaFX

左心房为你撑大大i 提交于 2019-12-11 04:03:18

问题


My goal is to read from a rich text formatted file and then display it's contents exactly how they appear with formatting in a JavaFX TextArea. I have already completed this with a plain text file (ANSI encoded). When I try to read from an rtf file it displays all the text as well as the formatting symbols. Is there a function that interprets these formatting symbols as it scans it in? It's been difficult trying to find an answer to this, so any help is greatly appreciated!

You can see my current file reading function from my Controller class:

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Scanner;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextArea;


public class Screen2Controller implements Initializable , ControlledScreen {

    ScreensController myController; 

   //read from file in Dropbox
   @FXML
   public void displayText() {
        try {
            //rtf reads text and format characters
            Scanner s = new Scanner(new File("C:/Users/EECSDept/Dropbox/EECS Hallway Display/Department Info/rtftest.rtf")).useDelimiter("\\s+");
            while (s.hasNext()) {
                dinfoTextArea.appendText(s.next() + " "); // read the next token
            }
        } 
        catch (FileNotFoundException ex) {
            System.err.println("File not found - check file path | "+ex);
        }

    } //end displaytext

    //must reference specific textarea with correct fxid
    @FXML TextArea dinfoTextArea;
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        displayText(); //call file reading function
    }



    public void setScreenParent(ScreensController screenParent){
        myController = screenParent;
    }

    @FXML
    private void goToScreen1(ActionEvent event){
       //go home
       myController.setScreen(ScreensFramework.screen1ID);
    }

    @FXML
    private void goToProgram(ActionEvent event){
       myController.setScreen(ScreensFramework.programID);
    }

    @FXML
    private void goToMap(ActionEvent event){
       myController.setScreen(ScreensFramework.mapID);
    }


} //end screen2controller

And this is the output to my text area: {\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}} {*\generator Riched20 6.2.9200}\viewkind4\uc1 \pard\sl240\slmult1\f0\fs22\lang9 This is a rtf document 12 3\par \tab Tab\par \b This is bold\par }

When I want this to be output:

This is a rtf document 12 3

___Tab

This is bold

来源:https://stackoverflow.com/questions/28573275/how-to-read-rtf-file-and-display-in-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!