JavaFX ScrollPane hold TextArea

Description

JavaFX ScrollPane hold TextArea

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

import javafx.application.Application;
import javafx.geometry.Pos;
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.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {
   protected TextField tfFileName = new TextField();
   protected TextArea taTextFile = new TextArea();

   @Override/*from  w w  w .j a va 2 s .  c o m*/
   public void start(Stage primaryStage) throws Exception {
      tfFileName.setPrefColumnCount(23);

      Button btView = new Button("View");

      HBox paneForTextField = new HBox();
      paneForTextField.getChildren().addAll(new Label("Filename"), tfFileName, btView);

      taTextFile.setEditable(false);
      taTextFile.setWrapText(true);

      // Create scroll pane
      ScrollPane scrollPane = new ScrollPane(taTextFile);

      // Create a vbox
      VBox pane = new VBox();
      pane.setAlignment(Pos.CENTER);
      pane.getChildren().addAll(scrollPane, paneForTextField);

      // Create and register handler
      btView.setOnAction(e -> {
         try {
            getTextFile();
         } catch (FileNotFoundException ex) {
            taTextFile.setText("Error! File Not Found.");
         }
      });
      Scene scene = new Scene(pane, 400, 200);
      primaryStage.setTitle("java2s.com");
      primaryStage.setScene(scene);
      primaryStage.show();
   }
   // Reads text from file and displays it in a text area
   private void getTextFile() throws FileNotFoundException {
      // Check if source file exists
      File file = new File(tfFileName.getText());
      if (!file.exists()) {
         taTextFile.setText(tfFileName.getText() + " does not exist");
      } else {
         String text = "";
         try (
               // Create input file
               Scanner input = new Scanner(file);) {
            while (input.hasNext()) {
               text += input.nextLine();
               text += "\n";
            }
            taTextFile.setText(text);
         }
      }
   }
}



PreviousNext

Related