JavaFX read from text file and display in textarea

26,263

Solution 1

      @FXML TextArea YourTextArea; //i think you already know about this

@Override
public void initialize(URL url, ResourceBundle rb) {
    try {
        Scanner s = new Scanner(new File("EECS.txt")).useDelimiter("\\s+");
        while (s.hasNext()) {
            if (s.hasNextInt()) { // check if next token is an int
                YourTextArea.appendText(s.nextInt() + " "); // display the found integer
            } else {
               YourTextArea.appendText(s.next() + " "); // else read the next token
            }
        }
    } catch (FileNotFoundException ex) {
        System.err.println(ex);
    }
}

or you can simply call your button's 'on action' method from initialize(). eg.

    @FXML public void displayTextOnButtonClick(){ //suppose this method gets fired when you click button

}

@FXML public void initialize(URL url, ResourceBundle rb) {
   displayTextOnButtonClick();
} 

Solution 2

Just put the code you wrote inside the displayTextOnButtonClick inside the initialize(). This is what initialize is meant for.

Initialize is called after processing the root node and it adds extra functionality(if defined) and data to the controls present in the fxml.

Share:
26,263
Maxwell
Author by

Maxwell

Updated on December 03, 2020

Comments

  • Maxwell
    Maxwell over 3 years

    I am new to JavaFX and JavaFX Scene Builder and have been researching and trying to figure out for weeks now how to simply read from a text file and display its contents in a textarea. I have a good file reading function in my controller class, but I can't figure out how to display the text file to the text area in the fxml document. I've learned how to click a button and make the file display in the text area, but I want to have the contents in the text area as soon as the GUI loads. If anyone has an idea how to go about doing this, your help will be greatly appreciated!

    The last button and text area (towards the end of the FXML document) is the button that prints my text file to netbeans, and the text area in which I would like the text to be dispalyed.

    Here is my code:

    Controller

    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;
    
    
    public class Screen2Controller implements Initializable , ControlledScreen {
    
        ScreensController myController;
    
        @Override
        public void initialize(URL url, ResourceBundle rb) {
            // TODO
        }
    
        public void setScreenParent(ScreensController screenParent){
            myController = screenParent;
        }
    
        @FXML
        private void goToScreen1(ActionEvent event){
           myController.setScreen(ScreensFramework.screen1ID);
        }
    
        @FXML
        private void goToProgram(ActionEvent event){
           myController.setScreen(ScreensFramework.programID);
        }
    
        private void displayText() throws FileNotFoundException {
            Scanner s = new Scanner (new File ("EECS.txt")).useDelimiter("\\s+");
            while (s.hasNext()) {
                if (s.hasNextInt()) { // check if next token is an int
                    System.out.print(s.nextInt()+" "); // display the found integer
                }       
                else {
                    System.out.print(s.next()+" "); // else read the next token
                }
            } //end while
        } //end main   
    } //end screen2controller
    

    FXML

    <?xml version="1.0" encoding="UTF-8"?>
    
    <?import javafx.scene.image.*?>
    <?import java.lang.*?>
    <?import java.util.*?>
    <?import javafx.scene.*?>
    <?import javafx.scene.control.*?>
    <?import javafx.scene.layout.*?>
    <?import javafx.scene.text.*?>
    
    <AnchorPane id="AnchorPane" prefHeight="650.0" prefWidth="1350.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="departmentdisplay.Screen2Controller">
      <children>
          <ImageView fitHeight="783.0" fitWidth="1398.0" layoutX="-4.0" layoutY="-80.0" pickOnBounds="true" preserveRatio="true">
             <image>
                <Image url="@nexus_blue.jpg" />
             </image>
          </ImageView>
          <ImageView fitHeight="149.0" fitWidth="1322.0" layoutX="20.0" layoutY="7.0" pickOnBounds="true" preserveRatio="true">
             <image>
                <Image url="@departinfohead.png" />
             </image>
          </ImageView>
      <Button layoutX="49.0" layoutY="26.0" mnemonicParsing="false" onAction="#goToScreen1" prefHeight="111.0" prefWidth="121.0">
             <graphic>
                <ImageView fitHeight="100.0" fitWidth="150.0" pickOnBounds="true" preserveRatio="true">
                   <image>
                      <Image url="@backarrow.png" />
                   </image>
                </ImageView>
             </graphic></Button>
          <SplitPane dividerPositions="0.20765027322404372" layoutX="928.0" layoutY="168.0" orientation="VERTICAL" prefHeight="185.0" prefWidth="415.0">
             <items>
                <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="95.0" prefWidth="183.0">
                   <children>
                      <Label layoutX="14.0" layoutY="23.0" prefHeight="96.0" prefWidth="158.0" text="                      Map" textAlignment="CENTER" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
                         <font>
                            <Font name="Arial Black" size="24.0" />
                         </font>
                      </Label>
                   </children>
                </AnchorPane>
                <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="176.0" prefWidth="158.0">
                   <children>
                      <TextArea prefHeight="151.0" prefWidth="242.0" text="Image" wrapText="true" AnchorPane.bottomAnchor="-7.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">       
                      </TextArea>
                   </children>
                </AnchorPane>
             </items>
          </SplitPane>
          <SplitPane dividerPositions="0.08057851239669421" layoutX="20.0" layoutY="168.0" orientation="VERTICAL" prefHeight="480.0" prefWidth="898.0">
             <items>
                <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
                   <children>
                      <Label layoutX="369.0" prefHeight="29.0" prefWidth="1062.0" text="                  Electrical Engineering &amp; Computer Science" textAlignment="CENTER" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
                         <font>
                            <Font name="Arial Black" size="24.0" />
                         </font>
                      </Label>
                   </children>
                </AnchorPane>
                <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
                   <children>
                      <TextArea fx:id="dinfoTextArea" layoutY="3.0" prefHeight="453.0" prefWidth="896.0" 
                     text="Text file text goes here" wrapText="true"
                      AnchorPane.bottomAnchor="-14.0" AnchorPane.leftAnchor="0.0"
                       AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="3.0">
                         </TextArea>
                   </children>
                </AnchorPane>
             </items>
          </SplitPane>
          <SplitPane dividerPositions="0.13286713286713286" layoutX="930.0" layoutY="365.0" orientation="VERTICAL" prefHeight="282.0" prefWidth="413.0">
             <items>
                <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="50.0" prefWidth="221.0">
                   <children>
                      <Label layoutX="92.0" layoutY="12.0" prefHeight="29.0" prefWidth="263.0" text="                  Programs" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
                         <font>
                            <Font name="Arial Black" size="24.0" />
                         </font>
                      </Label>
                  <Button layoutX="25.0" mnemonicParsing="false" onAction="#displayText" prefHeight="34.0" prefWidth="102.0" text="Go To Programs" />
                   </children>
                </AnchorPane>
                <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="176.0" prefWidth="158.0">
                   <children>
                      <TextArea layoutX="57.0" layoutY="-6.0" prefHeight="339.0" prefWidth="240.0"
                          text="Lorem ipsum " wrapText="true" AnchorPane.bottomAnchor="0.0"
                          AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" 
                          AnchorPane.topAnchor="0.0"> 
                      </TextArea>
                   </children>
                </AnchorPane>
             </items>
          </SplitPane>
      </children>
    </AnchorPane>
    
  • Maxwell
    Maxwell over 9 years
    Thank you @Muskan for answering! I actually did not think about the comment you placed next to myTextArea. I implemented those changes and the text area still did not display my text file. So then I just made my function append "hello world" to make sure the controller and fxml doc were communicating correctly and that worked. So is it a problem with my file reading function? I don't get any errors such as file not found.
  • Muskan
    Muskan over 9 years
    Your file reading function is working well. Does your .txt file contains characters in unicode format and you have saved it as ANSI encoded text file?
  • Maxwell
    Maxwell about 9 years
    Ah yes it was unicode, changed to ANSI and it worked fine. Thank you!
  • Maxwell
    Maxwell about 9 years
    Hello @Muskan would you happen to know how to read from an rich text formatted file and display its contents in correct format? More details on my question here: stackoverflow.com/questions/28573275/…
  • Maxwell
    Maxwell about 9 years
    Thank you @ItachiUchiha it worked like a charm! Would you happen to know how to read from an rtf file and display its contents with correct formatting? More details here: stackoverflow.com/questions/28573275/…