Java语言程序设计基础篇_编程练习题**16.10 (文本浏览器)

目录

题目:**16.10 (文本浏览器)

习题思路

代码示例 

 结果展示


题目:**16.10 (文本浏览器)

    编写一个程序在文本区域中显示一个文本文件,如图 16-40a 所示。用户在文本域中输人一个文件名,然后单击View按钮;在文本区域中会显示这个文件

  • 习题思路
  1. 新建私有类型的TextArea,Label、TextField、
  2. 再创建一个ScrollPane,传入参数TextArea
  3. 创建一个HBox,把Label和TextField添加到布局中,再另外新建一个Button同样添加到布局
  4. 创建BorderPane,把ScrollPane设置在中心,把HBox设置在底部
  5. 为按钮Button注册一个鼠标点击事件,事件被触发时检查TextField是否为空,不为空则以输入框内容为参数调用写入TextArea的方法
  6. (创建写入TextArea的方法) 用Scanner读取传入的String类型的路径,使用while循环读取行并添加到一个String中暂存,当文件没有下一行时将TextArea的内容设置为String中的内容
  7. 创建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();
	}
}
  •  结果展示

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值