EDIT 4
我创建了一个简单的示例,应该可以让您了解现在发生的情况。
现在发生的情况是,每当我单击按钮将“HELLO WORLD”打印到 TextArea 时,程序就会挂起并使用 100% 的 CPU。 Eclipse 控制台面板中也没有输出。
Main.java
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/application/test.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
MainController.java
public class MainController {
@FXML
private TextArea console;
private PrintStream ps = new PrintStream(new Console(console));
public void button(ActionEvent event) {
System.setOut(ps);
System.setErr(ps);
System.out.println("Hello World");
}
public class Console extends OutputStream {
private TextArea console;
public Console(TextArea console) {
this.console = console;
}
public void appendText(String valueOf) {
Platform.runLater(() -> console.appendText(valueOf));
}
public void write(int b) throws IOException {
appendText(String.valueOf((char)b));
}
}
}
编辑2:看来我的问题太长而且难以理解。我正在重组这个项目。
EDIT 3
我想我应该在这里展示一切。我想做的是一个 CLI 应用程序的简单 GUI 前端。我是一名CS学生,Java是我们的主要语言,所以这主要是为了练习。
我已经到处寻找了几个小时,但仍然没有解决这个问题。我尝试过像之前使用 Swing 一样进行操作。该方法适用于 Swing,但不适用于 JavaFX。
这是我的(当前)logger.java 类:
package application;
import java.io.*;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
public class ytdlLogger extends OutputStream implements Initializable
{
private TextArea loggerPane;
public ytdlLogger(TextArea loggerPane) {
this.loggerPane = loggerPane;
}
public void appendText(String valueOf) {
Platform.runLater(() -> loggerPane.appendText(valueOf));
}
@Override
public void initialize(URL location, ResourceBundle resources) {
OutputStream out = new OutputStream() {
@Override
public void write(int b) throws IOException {
appendText(String.valueOf((char)b));
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
@Override
public void write(int b) throws IOException {
// TODO Auto-generated method stub
}
}
我认为这没有任何实际问题。我还添加了 PrintStream 对象以将 MainController 类中的 System.setOut 和 System.setErr 重定向到 TextArea,但它也不起作用。
我还有另一个 Main 类,它是加载 FXML 的主要内容。我尝试从那里重定向输出,它几乎成功了。几乎是这样,因为我不再看到 Eclipse 内的控制台输出,我知道这是一个巨大的进步。
那么,这里似乎有什么问题呢?是因为FXML吗?我是 Java 和 JavaFX 的绝对初学者,这是我的第一个 JavaFX 应用程序。非常感谢任何指导。先感谢您。
EDIT 1
这是主类:
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/application/Main.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}