2
package client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ResourceBundle;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class HomeController implements Initializable {
@FXML
private Button btn;
@FXML
private TextArea txtarea;
@FXML
private TextField txtmsg;
Socket sock;
DataInputStream di;
DataOutputStream dout;
public void initialize(URL location, ResourceBundle resources) {
try {
sock = new Socket(InetAddress.getByName("localhost"), 8081);
System.out.println("Client Started....");
txtarea.setText("Client Started...");
di = new DataInputStream(sock.getInputStream());
dout = new DataOutputStream(sock.getOutputStream());
btn.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
try {
dout.writeUTF(txtmsg.getText().trim());
txtmsg.clear();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Task<Void> t = new Task<Void>() {
@Override
protected Void call() throws Exception {
// TODO Auto-generated method stub
String msg = di.readUTF().trim();
System.out.println(msg);
updateMessage("\nServer says : " + msg);
txtarea.appendText("\nServer says : " + msg);
return null;
}
};
new Thread(t).start();
// Executors.newSingleThreadExecutor().submit(t);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我在javaFX中创建聊天应用程序...上面的代码是为客户端.. 当服务器发送一些消息时,它不会出现在客户端textarea.houghough消息在控制台中收到。为什么textarea在javaFx中没有得到更新?
你能否给我提供一些解决方案?
好的,谢谢它的工作... bt我的文本区域没有被追加...任何解决方案? –
您可以使用'Bindings.concat',就像我在示例中所示。 – ItachiUchiha
@IchichiUchiha这不适用于你按下按钮的第二次和以后的时间。由于'txtArea.getText()'在计算绑定时立即返回当前文本,因此它总是将最后一条消息与原始文本连接起来。 (另外,由于对消息的更新是合并的,因此不保证以这种方式查看每条消息。)这里需要使用'Platform.runLater()'。 –