JavaFX TextArea set text from file

Description

JavaFX TextArea set text from file

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class Main extends Application {
   private double paneWidth = 250;
   private double paneHeight = 250;

   @Override// w ww.  j av  a  2 s.  c o  m
   public void start(Stage primaryStage) {
      BorderPane p = new BorderPane();
      p.setLeft(new Label("Filename"));
      TextField tfFilename = new TextField();
      p.setCenter(tfFilename);
      Button btView = new Button("View");
      p.setRight(btView);

      BorderPane pane = new BorderPane();
      TextArea ta = new TextArea();
      pane.setCenter(new ScrollPane(ta));
      pane.setBottom(p);
      p.setStyle("-fx-border-color: black");

      Scene scene = new Scene(pane, paneWidth, paneHeight);
      primaryStage.setTitle("java2s.com");
      primaryStage.setScene(scene);
      primaryStage.show();

      btView.setOnAction(e -> {
         // Get file name from the text field
         String filename = tfFilename.getText().trim();

         try {
            // Create a buffered stream
            Scanner input = new Scanner(new File(filename));

            // Read a line and append the line to the text area
            while (input.hasNext()) {
               ta.appendText(input.nextLine() + '\n');
            }
            input.close();
         } catch (FileNotFoundException ex) {
            System.out.println("File not found: " + filename);
         } catch (Exception ex) {
            System.out.println(ex.getMessage());
         }
      });
   }

   public static void main(String[] args) {
      launch(args);
   }
}



PreviousNext

Related