package fx;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
public class Exercise16_10 extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
TextArea textArea = new TextArea(); //文本区域
textArea.setPrefRowCount(10); //设置行数
textArea.setPrefColumnCount(30); //设置列数
TextField textField = new TextField(); //文本域
textField.setPromptText("FileName "); //设置提示文本
textField.setPrefColumnCount(28); //设置列数
Button view = new Button("View"); //按钮
view.setOnAction(event -> { //按钮注册动作事件
File file = new File(textField.getText()); //文件对象
if (!file.exists()) //如果文件不存在
textArea.setText("No such file exists");
else { //否则
try {
//创建输入流
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
byte[] bytes = new byte[255];
int length;
String text = "";
while ((length = inputStream.read(bytes)) != -1) //获取数据
text += new String(bytes, 0, length);
inputStream.close();
textArea.setText(text); //文本区域设置文本
} catch (Exception ex) {
}
}
});
BorderPane pane = new BorderPane(new ScrollPane(textArea));
pane.setBottom(new HBox(textField, view));
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.setTitle("Exercise16_10");
primaryStage.show();
}
}