简体   繁体   English

在Java按键上启动计时器

[英]Start timer on keypress, java

I want to, when i click the "d" button, start a timer. 我想在单击“ d”按钮时启动一个计时器。 This is to animate a player walking. 这是为了使播放器动画。 The timer doesn't start when i press the key, how do i do that? 按下键后计时器没有启动,该怎么办?

The code I have is this: 我的代码是这样的:

public class Game extends JPanel implements KeyListener {
//Player variables
private BufferedImage playerStanding;
private BufferedImage playerWalking;
private BufferedImage playerFrame;
private boolean walking = false;
private final int PLAYER_HEIGHT = 100;
private final int PLAYER_WIDTH = 100;
private final int INITIAL_X = 0;
private final int INITIAL_Y = 500;
private int x = INITIAL_X;
private int y = INITIAL_Y;
//The timer I want to start on keypress-> "d"
private Timer playerAnimationTimer;



public Game() {
    setPreferredSize(new Dimension(800, 800));
    setBackground(Color.CYAN);
    //Player
    try {
        playerStanding = ImageIO.read(getClass().getResource("player1.gif"));
        playerWalking = ImageIO.read(getClass().getResource("player2.gif"));
        playerFrame = playerStanding;


    }
    catch (IOException ex) {
        ex.printStackTrace();
    }

    playerAnimationTimer = new Timer(500, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            walking = !walking;
            playerFrame = walking ? playerWalking : playerStanding;
            x += 10;
            if (x > getWidth() - PLAYER_WIDTH) {
                x = INITIAL_X;
            }
            repaint();
        }
    });
    playerAnimationTimer.setRepeats(true);
}

public Dimension setPreferredSize() {
    return new Dimension(800, 800);
}



@Override
public void paintComponent(Graphics graphics) {
    super.paintComponent(graphics);

    Graphics2D graphics2D = (Graphics2D) graphics;
    if (playerFrame != null) {
        graphics2D.drawImage(playerFrame, x, y, PLAYER_WIDTH, PLAYER_HEIGHT, this);
    }


    graphics2D.dispose();
}

@Override
public void keyTyped(KeyEvent e) {
    //This doesn't work
    playerAnimationTimer.start();
}

@Override
public void keyPressed(KeyEvent e) {

}

@Override
public void keyReleased(KeyEvent e) {

}
}
//The class to hold the gamepanel
public class StartGame extends JFrame implements ActionListener {
private static JButton startGame = new JButton();

StartGame() {
    setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
    setSize(200, 100);
    setVisible(true);
    setBackground(Color.BLUE);
    setLocationRelativeTo(null);

    startGame.setText("Play!");
    startGame.setSize(100, 25);
    startGame.addActionListener(this);
    add(startGame);
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == startGame) {
        this.setVisible(false);
        new GameWindow();
    }
}
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new StartGame();
        }
    });
}
}

How could I make the timer start when I click the "d" button? 当我单击“ d”按钮时,如何使计时器启动?

Your KeyListener doesn't work because you never add the KeyListener to anything much less to a component that has focus, which is needed for a KeyListener to work. 您的KeyListener无法正常工作,因为您绝不会将KeyListener添加到具有焦点的组件中,这是KeyListener正常工作所必需的。

I suggest that you instead use Key Bindings as a cleaner safer way to capture the desired key press. 我建议您改用“键绑定”作为更安全的方法来捕获所需的按键。

As an aside, never dispose of a Graphics object that is given to you from the JVM. 顺便说一句,切勿处置JVM提供给您的Graphics对象。

For a better answer, please edit your code to make it comply with the mcve standard. 为了获得更好的答案,请编辑您的代码以使其符合mcve标准。 You should use no images files, and it should compile and run for us unaltered. 您不应该使用任何图像文件,并且应不更改地为我们编译和运行。

You could set the private Timer like you did and start it like this... 您可以像这样设置私有计时器并像这样启动它...

public void startTimer(){
   timer.start();
   timer.setRepeats(true);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM