我想将文件内容打印到 JFXTextArea
,但输出并非 100% 相同。
这是文件内容:
这是我的 JavaFX 程序的输出:
这是我的代码:
try {
InputStream inputstream = new FileInputStream("output.txt");
int data = inputstream.read();
while (data != -1) {
char aChar = (char) data;
out.appendText(String.valueOf(aChar));
System.out.print(aChar);
data = inputstream.read();
}
inputstream.close();
} catch (Exception ex) {
System.err.println(ex);
}
我尝试了 BufferReader
和 Scanner
但它们都得到了相同的结果。
请记住,控制台中的输出 100% 等于文件内容。
最佳答案
这是所使用字体的问题。控制台主要使用等宽字体,在对齐字符时效果很好。然而,JavaFX 使用的默认字体不是等宽字体。
您需要自己分配该系列的字体:
@Override
public void start(Stage stage) throws Exception {
JFXTextArea textArea = new JFXTextArea();
ToggleButton toggle = new ToggleButton("monospaced");
toggle.setSelected(true);
textArea.fontProperty().bind(
Bindings.when(toggle.selectedProperty()).then(Font.font("monospaced")).otherwise(Font.getDefault()));
textArea.setText(
"+-----------+----------------------+\n"
+ "| R1 | R2 |\n"
+ "+-----------+----------------------+\n"
+ "| **DONE** | ***DONE*** |\n"
+ "+-----------+----------------------+");
stage.setScene(new Scene(new VBox(toggle, textArea)));
stage.show();
}
请注意,绑定(bind)只是用于显示差异。通常你只需像这样设置字体:
textArea.setFont(Font.font("monospaced"));
关于java - 如何在文本区域打印文件内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54250570/