获取标题中提到的错误。描述以下情形(JavaFX 8):
Main.java
public class Main extends Application {
private Parent rootNode;
public static void main(final String[] args) {
Application.launch(args);
}
@Override
public void init() throws Exception {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/Main.fxml"));
rootNode = fxmlLoader.load();
}
@Override
public void start(Stage stage) throws Exception{
stage.setTitle("Proxy Server");
stage.setScene(new Scene(rootNode));
stage.show();
}
}
我有一个用于视图MainController.java
的控制器(Main.fxml
)。
MainController.java
public class MainController {
@FXML
private TextField inputUrl;
@FXML
private Button goButton;
@FXML
private TextArea outputTextArea;
@FXML
private TextField proxyServerAddress;
@FXML
private WebView webView;
@FXML
private void handleGoButtonAction(ActionEvent event) {
Window owner = goButton.getScene().getWindow();
ExecutorService threadPool = Executors.newFixedThreadPool(10);
StringTokenizer tokenizer = new StringTokenizer(proxyServerAddress.getText(), ":");
ClientWorker clientWorker = new ClientWorker(this.webView, this.outputTextArea,
tokenizer.nextToken(),
Integer.parseInt(tokenizer.nextToken()),
inputUrl.getText());
threadPool.execute(clientWorker);
}
}
从控制器的handleGoButtonAction
动作事件中,我传递了webView
的引用。在ClientWorker
内部,我从传递的WebEngine
引用中获取了webView
的实例:
ClientWorker.java
public class ClientWorker implements Runnable {
@FXML
private TextArea outputTextArea;
@FXML
private WebView webView;
private Socket socket;
private String proxyServerUrl;
private Integer proxyServerPort;
private String url;
public ClientWorker(WebView webView, TextArea outputTextArea, String proxyServerUrl, Integer proxyServerPort, String url) {
this.webView = webView;
this.outputTextArea = outputTextArea;
this.proxyServerUrl = proxyServerUrl;
this.proxyServerPort = proxyServerPort;
this.url = url;
try {
this.socket = new Socket(proxyServerUrl, proxyServerPort);
} catch (IOException e) {
log.error(e.getMessage());
}
}
public void run() {
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(this.url);
//flushes the stream
out.flush();
String feed = null;
StringBuilder sb = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//read from socket input stream (responses from server)
while ((feed = in.readLine()) != null) {
sb.append(feed);
sb.append("\n");
}
//settings server response to GUI
outputTextArea.setText(sb.toString());
WebEngine engine = webView.getEngine();
engine.loadContent(sb.toString());
return;
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
对于上述情况,我遇到了java.lang.IllegalStateException: Not on FX application thread; currentThread = JavaFX-Launcher
异常。 (我通过WebEngine加载的内容是字符串中的html)