Java黑皮书16.10(文本浏览器)

package sample;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

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

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        BorderPane borderPane1 = new BorderPane();
        borderPane1.setLeft(new Label("Filename"));
        TextField textField = new TextField();
        borderPane1.setCenter(textField);

        Button button_View = new Button("View");
        borderPane1.setRight(button_View);

        BorderPane borderPane2 = new BorderPane();
        TextArea textArea = new TextArea();
        borderPane2.setCenter(new ScrollPane(textArea));
        borderPane2.setBottom(borderPane1);
        borderPane2.setStyle("-fx-border-color: black");

        Scene scene = new Scene(borderPane2, 540, 270);
        primaryStage.setTitle("文本浏览器");
        primaryStage.setScene(scene);
        primaryStage.show();
        button_View.setOnAction(e -> {
            String filename = textField.getText().trim();
            try {
                Scanner input = new Scanner(new File(filename));
                while (input.hasNext()) textArea.appendText(input.nextLine() + '\n');
            } catch (FileNotFoundException ex) {
                System.out.println("File not find");
            }
        });
    }

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

运行结果

java白皮书中文版 java黑皮书_开发语言