2

我撞到了另一面墙。让我的按键输入工作后,我已经绞尽脑汁好几个小时了,我想创建一个暂停功能,这样如果再次按下相同的按键,timertask就会停止运行(即游戏暂停)

JPanel component = (JPanel)frame.getContentPane();
    component.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "space");
    component.getActionMap().put("space", (new AbstractAction(){
        public void actionPerformed(ActionEvent e){

            Timer timer = new Timer();

            timer.scheduleAtFixedRate(new TimerTask(){
            public void run(){
                    grid.stepGame();
                }
            },250, 250);



        }}));


        }

问题是我不能使用全局布尔 isRunning var 并在每次按下键时切换它,因为嵌套类中的 timerTask 方法(因此布尔 isRunning 必须声明为 final 才能访问......)。关于如何检测是否再次按下键或游戏是否已经运行的任何想法,以便我可以暂停/取消我的 timerTask。

非常感谢山姆

4

5 回答 5

6

由于这是一个 Swing 游戏,您应该使用 javax.swing.Timer 或 Swing Timer 而不是 java.util.Timer。通过使用 Swing Timer,您可以保证在 EDT 上调用间歇性调用的代码,这是 Swing 应用程序的一个关键问题,并且它还有一个暂停 Timer 的 stop 方法。您还可以为您的匿名 AbstractAction 类提供一个私有布尔字段,以检查该键是否是第一次按下。

此外,使用 Key Bindings 而不是 KeyListener 的荣誉和 1+。

例如,

  JPanel component = (JPanel) frame.getContentPane();
  component.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "space");
  component.getActionMap().put("space", (new AbstractAction() {
     private boolean firstPress = true;
     private int timerDelay = 250;
     private javax.swing.Timer keyTimer = new javax.swing.Timer(timerDelay , new ActionListener() {

        // Swing Timer's actionPerformed
        public void actionPerformed(ActionEvent e) {
           grid.stepGame();
        }
     });

     // key binding AbstractAction's actionPerformed
     public void actionPerformed(ActionEvent e) {
        if (firstPress) {
           keyTimer.start();
        } else {
           keyTimer.stop();
        }

        firstPress = !firstPress;
     }
  }));

另一个有用的选项是在按键时执行重复任务并在按键释放时停止它,这可以通过在按下和释放时获取击键来轻松完成:

KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true) // for key release
KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false) // for key press

例如:

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

public class SwingTimerEg2 {
   private JFrame frame;
   private Grid2 grid = new Grid2(this);
   private JTextArea textarea = new JTextArea(20, 20);
   private int stepCount = 0;

   public SwingTimerEg2() {
      frame = new JFrame();

      textarea.setEditable(false);
      frame.add(new JScrollPane(textarea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
      setUpKeyBinding();
   }

   void setUpKeyBinding() {
      final int timerDelay = 250;
      final Timer keyTimer = new Timer(timerDelay, new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            grid.stepGame();
         }
      });
      JPanel component = (JPanel) frame.getContentPane();
      final int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
      final String spaceDown = "space down";
      final String spaceUp = "space up";
      component.getInputMap(condition).put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false), spaceDown);
      component.getActionMap().put(spaceDown, (new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
            keyTimer.start();
         }
      }));
      component.getInputMap(condition).put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true), spaceUp);
      component.getActionMap().put(spaceUp, (new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
            keyTimer.stop();
         }
      }));

   }

   public void doSomething() {
      textarea.append(String.format("Zap %d!!!%n", stepCount));
      stepCount ++;
   }

   private static void createAndShowGui() {
      new SwingTimerEg2();
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }

}

class Grid2 {
   private SwingTimerEg2 stEg;

   public Grid2(SwingTimerEg2 stEg) {
      this.stEg = stEg;
   }

   void stepGame() {
      stEg.doSomething();
   }
}
于 2011-10-22T12:54:50.393 回答
0

在某处保留对 Timer 的引用,例如在您的游戏类中。当游戏暂停时取消计时器。这将取消任何当前计划的任务。然后,当游戏未暂停时,再次安排计时器,就像您在上面所做的那样。

public class Game {

    private Timer timer;

    public void pause() {
        if (timer != null) {
            timer.pause();
        }
    }

    public void startOrResumeGame() {
        if (timer == null) {
            timer = new Timer();
        } else {
            // Just in case the game was already running.
            timer.cancel();
        }
        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                    grid.stepGame();
                }
            }, 250, 250);

    }
}
于 2011-10-22T13:04:29.720 回答
0

最简单和肮脏的解决方案:

final boolean[] isRunning = new boolean[1];

你不想那样做——但假设周围有适当的同步,它就可以工作。

更好的是

final AtomicBoolean isRunning = new AtomicBoolean();

更好的是再次审查设计:全局状态通常意味着“全局问题”

于 2011-10-22T12:54:47.220 回答
0

可以很容易地避免最终的限定符要求——用final对类方法的调用替换你的内部方法(它有要求)。

于 2011-10-22T12:57:28.983 回答
0

不,您对为什么匿名课程需要 final 有错误的想法!只有局部变量才需要 Final(更确切地说,任何可能具有比给定对象更短的生存时间的变量)。

因此,类中的静态变量非常好,并且可以完美地工作!

编辑:示例:

public class Main {
    interface Test {
        void call();
    }

    public static volatile boolean running = true;

    public static void main(String[] args) {
        Test t = new Test() {
            @Override
            public void call() {
                System.out.println(Main.running);
            }
        };
        t.call();
        running = false;
        t.call();
    }
}
于 2011-10-22T12:59:12.727 回答