JTextField 加载

发布于 2024-12-13 19:56:54 字数 402 浏览 9 评论 0原文

我有问题.. 在我的代码中,我有它,以便文本应该输出到 JTextField。当我运行该程序时,它没有。但是,如果我直接在将文本放入 JTextField 的代码之后放置一个 JOptionPane 那么它就可以工作...

任何人都有一个解决方案可以在没有 JOptionPane 的情况下进行 JTextField 更新吗?

我的代码:

// Works:
JTextField.setText("String");
JOptionPane.showMessageDialog(null, "String");

// Doesn't Work:
JTextField.setText("String");
//JOptionPane.showMessageDialog(null, "String");

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");

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

摇划花蜜的午后 2024-12-20 19:56:54

可能会失败的原因有两个:

  1. 您正在从主 (Swing) 线程外部调用 setText()
  2. 您正在从主 (Swing) 线程中调用 setText() Swing) 线程

在第一种情况下,将调用包装在 SwingUtilities.invokeLater() 中。

在后一种情况下,您设置了文本,但阻塞了 Swing 线程,因此无法呈现更改。您将需要创建一个后台工作线程来完成这项工作,并使用 SwingUtilities.invokeLater() 从工作线程更新文本字段。

[编辑] 请参阅 Swing 教程,了解如何使用后台线程以及如何从那里更新 UI 的示例:http://download.oracle.com/javase/tutorial/uiswing/concurrency/interim.html

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

嘿哥们儿 2024-12-20 19:56:54

为什么不在文本更新后使用 repaint() 呢?

如果我没记错的话,应该解决文本不附加的问题。

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文