当前位置: 动力学知识库 > 问答 > 编程问答 >

java - JTextField loading

问题描述:

I'm having a problem..

In my code I have it so that text should output to a JTextField. when I run the program, it doesn't. However, if I directy after my code for putting text into the JTextField put a JOptionPane then it works...

Anyone have an solution to make the JTextField update without having the JOptionPane after?

My code:

// Works:

JTextField.setText("String");

JOptionPane.showMessageDialog(null, "String");

// Doesn't Work:

JTextField.setText("String");

//JOptionPane.showMessageDialog(null, "String");

网友答案:

There are two reasons why this might fail:

  1. You're calling setText() from outside the main (Swing) thread
  2. You're calling setText() from in the main (Swing) thread

In the first case, wrap the call in SwingUtilities.invokeLater().

In the latter case, you set the text but you're blocking the Swing thread, so the change can't be rendered. You will need to create a background worker to do the work and use SwingUtilities.invokeLater() to update the text field from your worker thread.

[EDIT] See the Swing tutorial for an example how to use background thread and how to update the UI from there: http://download.oracle.com/javase/tutorial/uiswing/concurrency/interim.html

网友答案:

Why not just use repaint() after the text update?

If memory serves me right that should address the issue of the text not appending.

分享给朋友:
您可能感兴趣的文章:
随机阅读: