Cannot show data in jTextField

I am writing socket programming. It has a graphical interface for the server and client. The graphical interface of the server has a text field that shows the word requested by the user. But I have trouble showing the word.

I tried

txtWord.setText(sentword); 

It does not show the word in the text box. But when I write it

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

then it shows the word in the text box and also shows it in the message box.

I tried redrawing (), but it works. Please offer me some solution as soon as possible.

+4
source share
2 answers

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

  • your Swing GUI doesn't care about the long and complex tasks that you perform in the background

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

  • The right way might be to use SwingWorker , which was created specifically to run a long and complex background job for the Swing GUI and output to the GUI for an event stream or EDT

  • or even easier to use Runnable in Thread , but make sure all output in the Swing GUI is queued in the Swing event stream by placing it in Runnable and invoking it with invokeLater()

  • A dirty hack is wrapping lines of code like this:

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

in invokeLater() , but in this case your GUI will not respond to Mouse or Keyboard events until Socket (in your case) finishes

+9
source

txtWord.requestFocus (); textField is not displayed until the window is above the text field and vice versa, or it focuses until you click on it. So ... just ask for the trick.

Also check the text size if you set at creation. Sometimes the text is not displayed if there is a size mismatch for example: txtWord.setSize (200, 24);

-1
source

Source: https://habr.com/ru/post/1435721/


All Articles