package fx;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
public class Exercise16_11 extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Histogram histogram = new Histogram();
TextField textField = new TextField(); //文本域
textField.setPromptText("FileName "); //设置引文
textField.setPrefColumnCount(28); //设置列数
Button view = new Button("View"); //按钮
view.setOnAction(event -> { //按钮注册动作事件
int[] counts = new int[26]; //计数数组
File file = new File(textField.getText()); //文件对象
if (!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();
for (int i = 0; i < text.length(); i++)
if (Character.isLetter(text.charAt(i))) //如果字符是字母,相应计数加1
counts[Character.toUpperCase(text.charAt(i)) - 'A']++;
histogram.setCounts(counts);
} catch (Exception ex) {
}
}
});
BorderPane pane = new BorderPane(histogram);
pane.setBottom(new HBox(textField, view));
pane.setPadding(new Insets(5));
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.setTitle("Exercise16_10");
primaryStage.show();
}
/** 内部类 */
public class Histogram extends Pane {
private int[] counts = new int[26]; //计数数组
private Rectangle[] rectangles = new Rectangle[26]; //矩形数组
public Histogram() {
HBox hBox = new HBox(2); //hbox对象
hBox.setAlignment(Pos.BOTTOM_CENTER); //设置对齐
hBox.setLayoutX(5); //设置x坐标
for (int i = 0; i < rectangles.length; i++) {
rectangles[i] = new Rectangle(12, 0); //创建矩形对象
rectangles[i].setStyle("-fx-fill: white; -fx-stroke: rgba(15,15,15,0.87);"); //矩形设置样式
Label label = new Label(String.valueOf((char) ('A' + i)), rectangles[i]); //创建带矩形节点的标签
label.setContentDisplay(ContentDisplay.TOP); //标签设置内容展示
hBox.getChildren().add(label); //hbox添加标签
}
this.getChildren().add(hBox);
}
/** 设置计数数组并重置矩形 */
public void setCounts(int[] counts) {
this.counts = counts;
for (int i = 0; i < this.counts.length; i++)
rectangles[i].setHeight(this.counts[i]); //设置矩形i的高度
}
}
}