这里的代码:
public class attrape_ball {
JFrame frame = new JFrame();
JPanel attrape = new JPanel();
public attrape_ball(pokeball pk) {
JLabel ramasseball = new JLabel("vous avez ramasser ");
attrape.add(ramasseball);
frame.setSize(200,100);
frame.add(attrape);
frame.setVisible(false);
}
@Override
public void afficherJframe() {
frame.setVisible(true);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();}
frame.dispose();
}
}
当我调用函数 afficherJFrame() 时,我想显示 JLabel,然后等待 3 秒,然后关闭 JFrame。 当我运行它时,不显示 JLabel。那就是问题所在。 (JFrame 在我想要的 3 秒后关闭)。
Swing 是单线程的,不是线程安全的。这意味着您不能在事件调度线程的上下文中执行长时间运行或阻塞操作(如
Thread.sleep
)。这也意味着您不应该从事件调度线程的上下文之外更新 UI 或 UI 所依赖的任何状态。
有关更多详细信息,请参阅Swing 中的并发。
本质上,
Thread.sleep
可能会阻止窗户被粉刷。
相反,使用 Swing
Timer
,例如...
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(32, 32, 32, 32));
JButton btn = new JButton("Show me the money");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFrame popup = new JFrame();
JLabel label = new JLabel("Money");
label.setBorder(new EmptyBorder(32, 32, 32, 32));
popup.add(label);
popup.pack();
popup.setLocationRelativeTo(TestPane.this);
popup.setVisible(true);
Timer timer = new Timer(3000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
popup.dispose();
}
});
timer.setRepeats(false);
timer.start();
}
});
add(btn);
}
}
}
有关更多详细信息,请参阅如何使用摆动计时器