在JFrame中更新JLabel [英] Updating a JLabel within a JFrame

查看:198
本文介绍了在JFrame中更新JLabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在这个网站和互联网上搜索了几个小时,试图弄清楚如何解决此问题.我正在创建一个游戏,这是我第一次使用图形.我想出了如何创建JFrame,JPanel和JLabel的方法,而我似乎无法解决的唯一问题是更新JLabel.假设我是这样开始的:

I've been searching around this site and the internet for hours trying to figure out how to fix this problem. I'm creating a game and it's my first time using graphics. I figured out how to create a JFrame, JPanel and JLabel, and the only problem I can't seem to get around is updating the JLabel. Let's say I start it out like this:

JLabel testing = new JLabel ("blah", JLabel.CENTER);
testing.setAlignmentX(0);
testing.setAlignmentY(0);
frame.add(testing);

我可以使用testing.setText("hi");来更改Thread.sleep(2500)之后的文本,但是JLabel的先前状态(表示"blah")仍然存在. 嗨"只是出现在顶部.我已经尝试过testing.setVisible(false);,还有很多其他事情,但是没有什么让我显示,隐藏和更改JLabel.

I am able to change the text after a Thread.sleep(2500) by using testing.setText("hi");, but the previous state of the JLabel (which says blah) is still there. The "hi" just appears on top. I've tried testing.setVisible(false);, and so many other things but nothing is letting me display the JLabel, hide it, and then change it.

任何想法可能有什么问题吗? 谢谢

Any ideas what could be wrong? Thanks

推荐答案

不要sleep或以其他方式阻止AWT事件调度线程(EDT).

Don't sleep or otherwise block on the AWT Event Dispatch Thread (EDT).

改为使用javax.swing.Timer.注意:在不同的程序包中,没有其他同名的类.

Use javax.swing.Timer instead. Note: not any other class of the same name in a different package.

            javax.swing.Timer timer =
                new javax.swing.Timer(2500, event -> {
                    testing.setText("hi");
                });
            timer.setRepeats(false);
            timer.start();

这篇关于在JFrame中更新JLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆