问题
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