gpt4 book ai didi

java - Thread.sleep() 延迟整个程序而不是仅延迟它之后的程序

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:41 26 4
gpt4 key购买 nike

差不多的标题。该代码应该绘制一个框,等待 1 秒,然后在不同的位置绘制一个新框并重新绘制。相反,它将等待 1 秒,然后绘制两个框。感谢您的帮助,如果我搞砸了格式,我深表歉意。

import javax.swing.*;
import java.awt.*;

public class GameRunner extends JPanel{
@Override
public void paintComponent (Graphics g){
int x = 0;
boolean directionRight = true;
g.setColor(Color.blue);
g.fillRect(300,400,100,100);
repaint();
try{
Thread.sleep(1000);
}
catch (Exception ex){}
g.fillRect(600,400,100,100);
repaint();
}
public static void main (String[] args){
JFrame frame = new JFrame("Submarine");
GameRunner gameRunner = new GameRunner();
frame.add(gameRunner);
frame.setSize(1200,700);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}

最佳答案

  • Thread.sleep(1000);会阻塞当前运行的线程
  • paintComponent 从事件调度线程的上下文中调用。
  • Swing 在处理完当前(在本例中为“paint”)事件之前不会更新 UI 的状态,这意味着当它在 Thread.sleep 处被阻塞时,不会更新任何内容在 UI 上,不会处理任何新事件。

Swing 是一个单线程框架。您永远不应在事件调度线程的上下文中执行任何阻塞或长时间运行的操作。

看看Concurrency in Swing更多详情和How to use Swing Timers寻求可能的解决方案。

作为旁注,如果 UI 或 UI 依赖于任何绘制方法中的任何变量,则永远不要修改状态。绘制应该只绘制组件的当前状态,永远不要修改它,这包括直接或间接调用repaint

例如……

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class GameRunner extends JPanel {

private int xPos = 300;

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.blue);
g.fillRect(xPos, 400, 100, 100);
repaint();
}

public GameRunner() {
Timer timer = new Timer(1000, new ActionListener() {
private boolean state = false;
@Override
public void actionPerformed(ActionEvent e) {
if (state) {
xPos = 300;
} else {
xPos = 600;
}
state = !state;
repaint();
}
});
timer.start();
}

@Override
public Dimension getPreferredSize() {
return new Dimension(700, 500);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new GameRunner());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

关于java - Thread.sleep() 延迟整个程序而不是仅延迟它之后的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34032900/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com