Updating a JLabel within a JFrame

爱⌒轻易说出口 提交于 2020-02-15 06:52:19

问题


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

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


回答1:


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

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


来源:https://stackoverflow.com/questions/59707842/updating-a-jlabel-within-a-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!