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

时间:2013-10-28 01:46:13

标签: java swing loops event-dispatch-thread

我做了有人告诉我做的游戏循环,添加摇摆计时器等(除了覆盖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 个答案:

答案 0 :(得分:3)

  1. javax.swing.Timer保证在EDT的上下文中调用已分配的actionPerformed的{​​{1}}方法
  2. 在EDT中运行无限循环现在阻止它,防止不断更新UI。
  3. 您的ActionListener应该更像......

    runGameLoop

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

    阅读

    了解更多详情。