简体   繁体   English

在 JFrame 中更新 JLabel

[英]Updating a JLabel within a JFrame

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.我想出了如何创建 JFrame、JPanel 和 JLabel,而我似乎无法解决的唯一问题是更新 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);

I am able to change the text after a Thread.sleep(2500) by using testing.setText("hi");我可以使用testing.setText("hi");Thread.sleep(2500)之后更改文本testing.setText("hi"); , but the previous state of the JLabel (which says blah) is still there. ,但 JLabel 的先前状态(即 blah)仍然存在。 The "hi" just appears on top. “嗨”只出现在顶部。 I've tried testing.setVisible(false);我试过testing.setVisible(false); , and so many other things but nothing is letting me display the JLabel, hide it, and then change it. ,还有很多其他的东西,但没有什么能让我显示 JLabel,隐藏它,然后改变它。

Any ideas what could be wrong?任何想法可能是错误的? Thanks谢谢

Don't sleep or otherwise block on the AWT Event Dispatch Thread (EDT).不要在 AWT 事件调度线程 (EDT) 上sleep或以其他方式阻塞。

Use javax.swing.Timer instead.请改用javax.swing.Timer 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM