3
我正在創建一個JavaFX
應用程序,我需要GUI來與類中的其他代碼進行交互,但是GUI和另一段代碼顯然無法運行,因爲沒有我爲他們製作不同的Thread
s運行。如何與JavaFX多線程
public class Client extends Application {
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage primaryStage){
primaryStage.setTitle("Hello world!");
Button btn = new Button();
btn.setText("Run Client");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try{runClient();}catch (Exception e){System.out.println("Exception Occurred, Server is down.");}
}
});
StackPane root = new StackPane();
root.getChildren().addAll(btn);
primaryStage.setScene(new Scene(root, 500, 500));
primaryStage.show();
}
public void runClient() throws Exception {
String sentence;
String modSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + "\n");
modSentence = inFromServer.readLine();
System.out.println("From Server: " + modSentence);
clientSocket.close();
}
runClient()
是服務器的客戶端。我需要GUI與客戶端進行通信,但我無法使新的Thread
同時運行它們。
爲什麼你不能讓一個新的主題? –
您可以根據需要創建儘可能多的線程,但最好使用'ExecutorService';唯一的問題是所有GUI任務都應該在GUI線程上(請參閱Platform#runLater) – fge
您能告訴我我該怎麼做嗎?我不知道我會在哪裏調整。 – ChrisEthanFox