自动更新JTextArea

发布于 2025-01-06 15:21:52 字数 211 浏览 1 评论 0原文

我对 Java 完全陌生,而且我处于一堵完整的砖墙上。

我的系统上有一个 JTextArea,我希望进行实时更新,因此当将某些内容添加到 table2(在我的数据库中)时,我的服务器会从数据库中提取新值,然后更新 JTextArea。

我完全不知道如何做到这一点,尽管我已经发现我需要使用 Thread 来让它工作。

非常感谢任何/所有帮助(我的时间有点紧迫)

Completely new to Java and I'm at a complete brick wall.

I have a JTextArea on my system that I'd like to have a live update, so when something is added to table2 (in my database), my server pulls the new values from the database and then updates the JTextArea.

I have absolutely no idea how to do this, though I have worked out that I need to use Thread to get it to work.

Any/all help is greatly appreciated (I'm a little pressed for time with this)

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

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

发布评论

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

评论(1

﹏半生如梦愿梦如真 2025-01-13 15:21:52

你可以做的是让你的线程在给定的时间段轮询你的数据库,或者让更新数据库的进程触发你的 GUI 类可以拾取的某种事件。

一旦发生这种情况,您就可以使用 SwingUtilities.invokeLater() 更新您的 JTextArea。像这样的事情应该做:

if (eventIsFired)
{
    final String jtextAreaText = ...
    SwingUtilities.invokeLater(new Runnable()
    {
        @Override
        public void run()
        {
            jTextArea.setText(jTextAreaText);
        }            
    });
}

假设jTextArea是您实际的JTextArea,它被声明为全局变量。 jTextAreaText 需要声明为final,以便可以通过内部类访问它。

What you can do is have your thread poll your database at given periods of time, or else, have the process which is updating the database fire some kind of event which your GUI class can pick up.

Once this happens, you can then use the SwingUtilities.invokeLater() to update your JTextArea. Something like this should do:

if (eventIsFired)
{
    final String jtextAreaText = ...
    SwingUtilities.invokeLater(new Runnable()
    {
        @Override
        public void run()
        {
            jTextArea.setText(jTextAreaText);
        }            
    });
}

The assumption is that jTextArea is your actual JTextArea which is declared as a global variable. jTextAreaText will need to be declared final so that it can be accessed through the inner class.

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