我正在尝试使用Platform.runLater
从另一个实现Runnable
的类更新TextArea。
我在一个类中有我所有的GUI(我的TextArea所在的位置),我正在创建一个new server
线程并在创建gui时运行它。我正在尝试使用Platform.runLater
主题中的Server
更新我的TextArea
,但Platform.runLater
无法访问我的TextArea。
public class SimulationWindow {
public SimulationWindow instance() {
return this;
}
public static void DisplaySimulationWindow() throws FileNotFoundException {
Stage SimuStage = new Stage();
SimuStage.initModality(Modality.APPLICATION_MODAL);
SimuStage.setTitle("Simulation Window");
Server myServer = new Server(instance());
Thread serverThread = new Thread(myServer);
serverThread.start();
TextArea serverTextArea;
.
.
.
}
public class Server implements Runnable {
@Override
public void run() {
while(true){
whileConnected();
.
.
}
private void whileConnected() throws IOException {
sendMessage(message);
do {
try {
message = (String) input.readObject();
showMessage(message);
.
.
.
}
private void showMessage(String x) {
Platform.runLater(() -> serverTextArea.appendText(x));
}
我尝试将我的SimulationWindow实例传递给Server构造函数,就像他们在这里一样:Modifying JavaFX gui from different thread in different class
但Java不会让我的SimulationWindow实例作为Server construtor的参数传递。 其他解决方案将Server和SimulationWindow类保持为一,但我希望将它们分开。 任何提示都表示赞赏!
答案 0 :(得分:1)
我解决了这个问题,正如kleopatra建议的那样。我将TextArea传递给了我的Server构造函数。我想从GUI类更新GUI中的TextArea,以及从Server类中的客户端获取消息时。 (我在SimuWindow()中创建并启动我的服务器)
public class myGUI{
public void SimuWindow(){
//this method creates all the GUI.
Server myServer = new Server(serverTextArea);
Thread serverThread = new Thread(myServer);
serverThread.start();
sendingTest = new TextField();
sendingTest.setPromptText("test communication here");
sendingTest.setOnAction(event -> {
String message = new String ("\nServer says: ");
message = message + sendingTest.getText();
serverTextArea.appendText(message);
myServer.sendMessage(message);
sendingTest.clear();
});
}
}
public class Server implements Runnable{
//This is my server class that connects and listens to clients
TextArea mytextArea;
public Server(TextArea x) {
this.mytextArea = x;
}
private void whileConnected() throws IOException {
do {
try {
message = (String) input.readObject();
showMessage(message);
}catch(ClassNotFoundException classNotFoundException) {
System.out.println("\n i dont know the message");
}
}while(!message.equals("Disconnected"));
private void showMessage(String mess) {
Platform.runLater(() -> mytextArea.appendText(mess));
}
}
我在我的客户端类上做了同样的事情。谢谢你的帮助。