gpt4 book ai didi

java - 如何在游戏循环中调用 EDT?

转载 作者:行者123 更新时间:2023-12-01 23:28:54 25 4
gpt4 key购买 nike

我按照别人告诉我的方式处理我的游戏循环,添加了 Swing 计时器等(除了重写paintComponent,因为它在这种情况下不适用),但我的游戏循环拒绝调用事件调度线程。因此,JFrame 不会关闭,键盘输入也已过时。我可以手动调用 EDT 还是我遗漏了什么?

public class Window extends JFrame implements KeyListener{
private static final long serialVersionUID = 1L;
JPanel panel;
public static int screenX = 500;
public static int screenY = 500;
private int w = 0, h = 0;
public Window(){
super("FileTyper");
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.setSize(506,533);
super.setResizable(false);
panel = new JPanel();
super.getContentPane().add(panel);
super.setFocusable(true);
addKeyListener(this);

super.setVisible(true);
}
public void update(){
w++;h++;
if(w>500){
w = 0;
h = 0;
}
}
public void render(Graphics2D g){
g.setColor(Color.CYAN);
g.fillRect(0,0,500,500);
g.setColor(Color.black);
g.fillOval(0, 0, w, h);
}
@Override
public void keyPressed(KeyEvent e) {

}
@Override
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_F9:
panel.getGraphics().setColor(Color.green);
panel.getGraphics().drawRect(0, 0, 100, 100);
break;
case KeyEvent.VK_F10:
break;
}

}
@Override
public void keyTyped(KeyEvent arg0) {

}

}

 public class Boxy {
public Window window;
boolean running = true;
private BufferedImage offscreen;

public static void main (String args[]){
// Boxy box = new Boxy();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
begin();

}
});
}
public Boxy(){
//initialize variables

}
public void gameLoop(){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
init();
while(running){
update();
render();
delay();
}
}
});

}
public void runGameLoop()
{
Timer timer = new Timer(20, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
gameLoop();
}
});
timer.start();
}
private void init(){
window = new Window();
offscreen = new BufferedImage(Window.screenX,Window.screenY,BufferedImage.TYPE_INT_RGB);
}
private void update(){
window.update();
}
private void render(){
Graphics2D g = (Graphics2D) offscreen.getGraphics();
window.render(g);
Graphics2D g2 = (Graphics2D) window.panel.getGraphics();
g2.drawImage(offscreen,0,0,null);

}
private void delay(){
try {Thread.sleep(10);} catch (InterruptedException ex) {System.out.println("ERROR: Delay compromised");}
}
public static void begin(){
Boxy box = new Boxy();
box.runGameLoop();
}

}

最佳答案

  1. javax.swing.Timer 确保在 EDT 上下文中调用所分配的 ActionListeneractionPerformed 方法
  2. 在 EDT 中运行无限循环现在会阻止它,从而阻止更新 UI。

你的runGameLoop应该看起来更像......

public void runGameLoop()
{
Timer timer = new Timer(20, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
update();
render();
}
});
timer.start();
}

在实现任何建议之前,建议尝试了解这些建议想要实现的目标......

通读一下

了解更多详情。

关于java - 如何在游戏循环中调用 EDT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19626044/

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