目录
题目:**16.10 (文本浏览器)
编写一个程序在文本区域中显示一个文本文件,如图 16-40a 所示。用户在文本域中输人一个文件名,然后单击View按钮;在文本区域中会显示这个文件
-
习题思路
- 新建私有类型的TextArea,Label、TextField、
- 再创建一个ScrollPane,传入参数TextArea
- 创建一个HBox,把Label和TextField添加到布局中,再另外新建一个Button同样添加到布局
- 创建BorderPane,把ScrollPane设置在中心,把HBox设置在底部
- 为按钮Button注册一个鼠标点击事件,事件被触发时检查TextField是否为空,不为空则以输入框内容为参数调用写入TextArea的方法
- (创建写入TextArea的方法) 用Scanner读取传入的String类型的路径,使用while循环读取行并添加到一个String中暂存,当文件没有下一行时将TextArea的内容设置为String中的内容
-
创建Scene并运行代码
-
代码示例
编程练习题16_10TextBrowser.java
package chapter_16;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
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.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class 编程练习题16_10TextBrowser extends Application{
private TextField tfPath = new TextField();
private Label label = new Label("FilePath",tfPath);
TextArea textArea = new TextArea();
@Override
public void start(Stage primaryStage) throws Exception {
textArea.setWrapText(true);
ScrollPane scrollPane = new ScrollPane(textArea);
HBox hBox = new HBox(10);
hBox.setAlignment(Pos.CENTER);
label.setContentDisplay(ContentDisplay.RIGHT);
Button btView = new Button("View");
hBox.getChildren().addAll(label, tfPath, btView);
BorderPane borderPane = new BorderPane();
borderPane.setCenter(scrollPane);
borderPane.setBottom(hBox);
btView.setOnMouseClicked(e ->{
if(tfPath.getText() != "") {
try {
String path = tfPath.getText();//.replace("\\", "/")
write(path);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
});
Scene scene = new Scene(borderPane);
primaryStage.setTitle("编程练习题16_10TextBrowser");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
public void write(String path) throws FileNotFoundException{
File file = new File(path);
String s = "";
Scanner input = new Scanner(file);
while(input.hasNextLine()) {
String line = input.nextLine();
s += line+"\n";
}
textArea.setText(s);
input.close();
}
}
-
结果展示