java - 按键绑定(bind)没有响应

标签 java swing key-bindings key-events

我遵循了某人在另一个问题上发布的用于控制对象的键绑定(bind)的示例。为了简单起见,它所控制的只是在按下 VK_UP 时打印“woo”,但它并没有这样做。

来自here的一些代码我仍然无法开始工作。

主要内容如下

import javax.swing.*;

@SuppressWarnings("serial")
public class apples extends JFrame {

    static boolean running;

public static void main(String[] args){
    JFrame f = new JFrame();
    Peach p = new Peach();
    f.getContentPane().add(new test());
    f.add(new test());
    f.add(p);
    f.setSize(400,250);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
    p.run();
    }


}

这是关键绑定(bind)内容

    import java.awt.*;
import java.awt.event.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;


@SuppressWarnings("serial")
public class Peach extends JPanel {

    public void paint(Graphics g){
        setOpaque(false);
        super.paintComponent(g);
        this.setBackground(Color.WHITE);

        g.setColor(Color.BLACK);
        g.fillOval(x, y, br, br);

        g.drawString("Sort of Pong?", 157, 20);

        g.setColor(Color.BLACK);
        g.fillRect(paddlex, paddley, psizex, psizey);

        //g.setColor(new Color(51, 255, 204));
        //g.fillRect(100, 100, 80, 100);
        repaint();
    }



public void Panel(){    Thread go = new Thread();
    go.start(); }

    int xpos;
    final int left = -1; //left increment
    final int right = 1; //right increment
    int up = -1; // up increment (negative because down is revered in coordinates)
    int down = 1; // down increment
    boolean check = true; // moving or not
    int x =200; // ball position x
    int y=100; // ball position y
    boolean rightmove = true; // moving right or left
    boolean leftmove = false; // moving left
    boolean upmove = true; // moving up
    boolean downmove = false; // moving down
    int paddlex = 100; // paddle position x
    int paddley = 100; // paddle position y
    int psizex = 100; // paddle size in x dimension 
    int psizey = 100; // paddles size in y dimension
    int cdy; // for checking other side for collisions
    int cdx; // for checking other side for collisions
    int br = 8; // ball radius
    boolean shipupmove = false;
    boolean shipdownmove = true;
    int shipspeed = 1;
    boolean goup;
    long counter = 0;

    public void calc(){
        cdy = psizey + paddley; // for checking other side for collisions
        cdx = psizex + paddlex; // for checking other side for collisions
    }

    public void run(){
        while(true){
            move();
            collisiond();
            calc();
            counter++;
            try
            {
            Thread.sleep(8);
            }
            catch(InterruptedException ex)
            {
                        }
        }
    }

    public void move(){
            if (rightmove){
                if(x <377){
                    x = (x+right);
                }else{rightmove = false; leftmove = true;}
            }
    if(leftmove)
        if(x > 0){                      
        x = (x-right);
        }else{rightmove = true; leftmove= false;}


    if (downmove){
        if(y <205){
            y = (y+down);
        }else{downmove = false; upmove = true;}
    }
    if(upmove)
            if(y > 0){                      
                y = (y+up);
        }else{downmove = true; upmove= false;}  

}

    public void collisiond(){
        if(leftmove && (x ==(cdx+1) || x == (cdx-1) || x == cdx)&& y >= paddley-br && y <= cdy){
            leftmove = false; rightmove = true;
        }
        if(rightmove && (x ==(paddlex-br+1) || x == (paddlex-br-1) || x == paddlex-br) && y >= paddley && y <= cdy){
            rightmove = false; leftmove = true;
        }
        if(upmove && ((y == cdy+1) || (y == cdy-1) || (y == cdy)) && x >= paddlex && x<= cdx){
            upmove = false; downmove = true;
        }
        if(downmove && ((y == paddley - br +1) || (y == paddley - br -1) || (y == paddley - br)) && x > paddlex && x < cdx){
            downmove = false; upmove = true;
        }
    }

    public void movepaddle(){
        if(shipupmove && paddley !=0){
            this.paddley = paddley - 1  ;
        }
        if (shipdownmove && paddley < (205-psizey)){
            this.paddley = paddley + 1;
        }
        if(paddley < 16){
            shipupmove = false; shipdownmove = true;
        }
        if(cdy > 189){
            shipupmove = true; shipdownmove = false;
        }
        repaint();


}
}
class test extends JPanel{

        private static final long serialVersionUID = 1L;
        private Map<Direction, Boolean> directionMap = new HashMap<Direction, Boolean>();
        int DELAY = 5;

        enum Direction {
            UP(KeyEvent.VK_UP,true),
            DOWN(KeyEvent.VK_DOWN, false);
            private int KeyCode;
            boolean moveing;



            Direction(int KeyCode, boolean moveing) {
                this.KeyCode = KeyCode;
                this.moveing = moveing;

            }

            public int getKeyCode(){
                return KeyCode;
            }
            public boolean moveing(){
                return moveing;
            }

        }

    public test(){

        for(Direction direction : Direction.values()){
        directionMap.put(direction, false);

        }
        setBindings();  
        Timer timer = new Timer(5, new TimerListener());
        timer.start();
    }   
    private void setBindings(){
        InputMap in = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap act = getActionMap();
        for(final Direction d : Direction.values()){
            KeyStroke press = KeyStroke.getKeyStroke(d.getKeyCode(), 0 ,false);
            KeyStroke rel = KeyStroke.getKeyStroke(d.getKeyCode(),0,true);
            in.put(press, "key pressed");
            in.put(rel, "key released");
            act.put(d.toString()+"pressed", new AbstractAction(){

                private static final long serialVersionUID = 1L;

                public void actionPerformed(ActionEvent e) {
                    directionMap.put(d, true);      
                }       
            });
            act.put(d.toString()+"released", new AbstractAction(){

                private static final long serialVersionUID = 1L;

                public void actionPerformed(ActionEvent e) {
                                directionMap.put(d, false);
                }
            });
        }

    }

public class TimerListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            for(Direction d : Direction.values()){
                if(directionMap.get(d)){
                    if(d.moveing()){
                        System.out.println("woo");
                    }
                }
            }

        }


    }


}

如有任何见解,我们将不胜感激,谢谢

最佳答案

分配给InputMap的“actionMapKey”Object必须与您在ActionMap中使用的相同

例如...

in.put(press, "key pressed");
in.put(rel, "key released");
act.put("key pressed", new AbstractAction(){...}

关于java - 按键绑定(bind)没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15736836/

相关文章:

java - 数据库序列的 Hibernate 映射和 java 代码

java - 基数排序数字比较

java - IPageLayout下添加keyevent切换ViewPart

java - ActionListener 是 java 中的线程吗?

c# - 条件键绑定(bind)

emacs - emacs 中元命令的用户 super 键

java - 如果 TestNG 不尝试运行 JUnit 测试,我的 Maven 项目如何同时运行 JUnit 和 TestNG?

java - 在 Java 2D 游戏中, Sprite 没有朝正确的方向移动

java - 将 JButton 数组添加到 JFrame 时出现 NullpointerException

ALT+0 的 WPF 键绑定(bind)不起作用