等待在循环内按下一个键

时间:2013-08-20 04:27:34

标签: java keyboard awt wait keylistener

我有一个java应用程序,我想等待一个键被按下来执行另一个动作。直到现在我找到了:

public void keyPressed(KeyEvent e) {
  if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
        //Right arrow key code
  }
}

但是我想让它在一个循环中或等待密钥匹配的东西。

请帮忙。

更新

我希望程序等到按下该键并按下该键时我想触发另一个动作。例如:

public void something(){
  //do something
  wait until a key is pressed
  if( key pressed is a arrow key){
    something();
  }else{
    wait for the key to be pressed
  }
}

public void dootherthing(){
 //do other thing
}

我正在摇摆,我不希望GUI不负责任。即当我通过点击按钮调用dootherthing时。它应该这样做,等待应该结束。

3 个答案:

答案 0 :(得分:3)

Swing(和大多数GUI)是事件驱动的环境。也就是说,有些事情会发生,你会对此做出反应。

有一个循环等待某种行为是一种反直觉(恕我直言)。

一般来说,如果可以的话,你应该避免使用KeyListener。他们关注的重点是问题。 key bindings API有办法克服这一限制。

它允许您针对KeyStroke注册Action,并允许您的程序坐下来等待事情发生......

enter image description here

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;

public class KeyBindings {

    public static void main(String[] args) {
        new KeyBindings();
    }

    public KeyBindings() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

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

    public class TestPane extends JPanel {

        public TestPane() {

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 1;
            gbc.gridy = 0;

            add(new KeyPane(KeyEvent.VK_UP, 0), gbc);

            gbc.gridy = 2;
            add(new KeyPane(KeyEvent.VK_DOWN, 0), gbc);

            gbc.gridx = 0;
            gbc.gridy = 1;
            add(new KeyPane(KeyEvent.VK_LEFT, 0), gbc);

            gbc.gridx = 2;
            add(new KeyPane(KeyEvent.VK_RIGHT, 0), gbc);

        }
    }

    public class KeyPane extends JPanel {

        public KeyPane(int keyCode, int modifier) {

            setBorder(new LineBorder(Color.DARK_GRAY));

            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(keyCode, modifier, false), "keyPressed");
            im.put(KeyStroke.getKeyStroke(keyCode, modifier, true), "keyReleased");

            am.put("keyPressed", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    setBackground(Color.RED);
                }
            });

            am.put("keyReleased", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    setBackground(UIManager.getColor("Panel.background"));
                }
            });

        }

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

}

答案 1 :(得分:0)

你可以写一个关键的听众

我找到了一个包含Java WebStart示例和源代码的Java教程。看似获胜者是 KeyEvent.getKeyLocation()

KeyEvent.KEY_LOCATION_STANDARD
KeyEvent.KEY_LOCATION_LEFT
KeyEvent.KEY_LOCATION_RIGHT
KeyEvent.KEY_LOCATION_NUMPAD
KeyEvent.KEY_LOCATION_UNKNOWN

参考文献:
How to tell which SHIFT key was pressed?

答案 2 :(得分:0)

每当按下一个键时,将始终调用

keyPressed方法,那么为什么需要它在循环中呢? 从描述中看,你似乎正在开发一个打字游戏,如果是这样你就可以在JavaFX中使用Timeline类。

我在JavaFX中开发了一个非常simple typing game来查看它(代码没有正确组织)。