Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not able to show data in a jTextField

I am writing a socket programming. It has GUI for server and client. In the server GUI there is a textfield which shows the word requested by user. But I am having problem in showing the word.

I have tried

txtWord.setText(sentword);

It is not showing the word in the textfield. But when I write this

txtWord.setText(sentword);
JOptionPane.showMessageDialog(null, "the requesed word is: "+sentword);

then it shows the word in textfield and also shows it in the messagebox.

I have tried repaint() but it dint work. Please suggest me some solution as soon as possible

like image 614
user1691881 Avatar asked Feb 19 '23 02:02

user1691881


1 Answers

as @Binyamin Sharet correctly commented, you have a Concurrency in Swing issue.

  • your Swing GUI doesn't care about long and hard tasks you're running in the background

  • even JTextField#setText() is declared as thread safe, output from Socket (i.e.) by default never notified Event Dispatch Thread

  • correct way could be to use a SwingWorker that has been created specifically to run long and hard tasks background to the Swing GUI and output to the GUI on event thread or EDT

  • or even easier is to use a Runnable in a Thread but making sure that all output to the Swing GUI is queued on the Swing event thread by placing it in a Runnable and calling it with invokeLater()

  • A dirty hack is to wrap code lines like so:

txtWord.setText(sentword);
JOptionPane.showMessageDialog(null, "the requesed word is: "+sentword);

into invokeLater(), but in this case your GUI will be unresponsive to Mouse or Keyboard events until Socket (in your case) ended

like image 89
mKorbel Avatar answered Feb 24 '23 04:02

mKorbel