Witam
Napisałem prostą aplikację typu client-serwer.
Z serwera z JTextField pobierany jest tekst po wciśnięciu JButton'ai wysyłany do clienta.
Client posiada JTextArea, w którym chcę wyświetlać tekst. Mam problem z odświeżaniem/edycją obecnego tekstu w tym polu tekstowym(clienta). Każda nowa wiadomość, którą wyśle, tworzy nowe pole tekstowe przez co sypie się cały Client (pola nakładają się na siebie itp)
Zamieszczam fragmentu Clienta dotyczący połączenia i tekstu:
//nasluchiwanie na porcie 8189 na ip //no-ip TO DO
try
{
Socket s = new Socket("127.0.0.1", 8189);
try
{
//
InputStream inStream = s.getInputStream();
Scanner in = new Scanner(inStream);
while (in.hasNextLine())
{
//
String line = in.nextLine();
JTextArea lbl = new JTextArea(line);
lbl.revalidate();
//w labelu wyswietlany bedzie tekst wyslany z serwera
lbl.setBounds(0, 200, 480, 100);
ScrollPane sc = new ScrollPane();
sc.setBounds(0, 0, 480, 100);
panel1.add(sc);
sc.add(lbl);
lbl.setEditable(true);
lbl.setEnabled(true);
}
}
finally
{
s.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
Oraz serwera:
try
{
ServerSocket s = new ServerSocket(8189);
Socket incoming = s.accept();
try
{
InputStream inStream = incoming.getInputStream();
OutputStream outStream = incoming.getOutputStream();
Scanner in = new Scanner(inStream);
final PrintWriter out = new PrintWriter(outStream, true);
out.println("You are connected to server");
final JTextField lbl2 = new JTextField("Client connected to server");
lbl2.setBounds(0, 300, 300, 25);
panel1.add(lbl2);
lbl2.setVisible(true);
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
out.println(lbl2.getText());
System.out.println(lbl2.getText());
}
});
while (in.hasNextLine())
{
String line = in.nextLine();
System.out.println(line);
}
}
finally
{
s.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}