I'm having trouble using a JTextArea. I need every time something happens on my system, an info is added in real time. However, it does not appear anything.
I've tried to use setText()
and append()
, but neither worked. However, if I do this here
JOptionpane.showMessageDialog(null, JtextArea.getText())
It returns everything I had written before but was not showing up in it.
I've already tried using repaint()
too and nothing.
Has anyone ever been through this?
Here's a piece of code. When I click on a button, it has this call:
if (!isStartServer()) {
area.append("Iniciando servidor de aplicação...\n");
Integer portaSocket = Integer.parseInt(tfPorta.getText());
Integer limite = Integer.parseInt(tfLimite.getText());
setStartServer(true);
StartServidor s = new StartServidor(portaSocket, limite, this);
new Thread(s).start();
btStart.setText("Stop Server");
}else{
System.exit(0);
}
In this way, StartServer has become a Thread, which is usually where I will write the messages in JtextArea. When I did not have this "StartServer" as a Thread, it did not update the JtextArea when I called the writeTextArea (String msg);
StartServer Code:
public void run() {
setPortaSocket(getPortaSocket());
setLimite(getLimite());
try {
setServerSocket(new ServerSocket(getPortaSocket()));
writeTextArea("Ouvindo a porta " + getPortaSocket() + "...");
while (servidor.isStartServer()) {
setSocketCliente(getServerSocket().accept());
setUser(new User());
getUser().setCliente(getSocketCliente());
scanner = new Scanner(getUser().getCliente().getInputStream());
if (scanner.hasNext()) {
getUser().setNome(scanner.nextLine());
}
writeTextArea(getUser().getNome() + " conectou-se.");
if (!clientes.containsKey(getUser().getNome())) {
clientes.put(getUser().getNome(), getUser());
getUser().setIpComputador(getUser().getCliente().getInetAddress().getHostAddress());
getUser().setNomeComputador(getUser().getCliente().getInetAddress().getHostName());
ServidorReadMessage read = new ServidorReadMessage(getUser(), this);
new Thread(read).start();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (getServerSocket() != null) {
getServerSocket().close();
}
if (getSocketCliente() != null) {
getSocketCliente().close();
}
if (scanner != null) {
scanner.close();
}
} catch (IOException e) {
}
}
}
In this way, you are writing correctly, but I do not know if it is the best way, I do not know nor do I know if it is correct to do so. So I'd like your help. I've looked at the documentation and it says nothing about it.