简体   繁体   中英

Key Bindings not responding

I followed an example someone posted on another question for key bindings to control an object. For the sake of simplicity all it is controlling is printing "woo" when VK_UP is pressed but it doesn't do that.

some code from here that I still can't manage to get working.

Heres the main

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();
    }


}

and here is the key binding stuff

    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");
                    }
                }
            }

        }


    }


}

any insight would be appreciated thank you

The "actionMapKey" Object assign to the InputMap MUST be the same you use in the ActionMap

For example...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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