【问题标题】:Key Bindings not responding键绑定没有响应
【发布时间】:2013-04-01 02:21:20
【问题描述】:

我遵循了某人在另一个问题上发布的示例,用于控制对象的键绑定。为简单起见,它所控制的只是在按下 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();
    }


}

这里是键绑定的东西

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

        }


    }


}

任何见解将不胜感激,谢谢

【问题讨论】:

  • Peach 类到底是什么?它的代码在哪里?你知道吗,通过将它添加到 JFrame 的 contentPane 中,你会掩盖之前添加的组件。此外,apples(更好,Apples)类不应该扩展 JFrame,因为它的行为不像 JFrame。最后,如果您希望其他人能够更好地理解您的代码,请遵守 Java 的命名约定。
  • 顺便说一下,其中一些代码看起来像我的,或者我的 mKorbel 代码。此外,您不应该将测试类 twice 添加到 JFrame。
  • Peach 课程专注于一些基本物理的小动画,但它不相关,所以我没有包括它。对于任何命名错误,我深表歉意,我会努力使其更简洁。
  • 通过在上面的代码中保留您的 Peaches 代码,您的代码对于我们来说是不可编译的。以后请避免这种情况。
  • 顺便说一下,您的 paint() 方法完全搞砸了。首先,您应该覆盖paintComponent() 而不是paint()。您不应该更改 peinting 方法中的组件属性(即 setOpaque()、setBackground())。而且您绝对不想在方法中调用 repaint() 。是时候阅读Swing tutorial了。它包含有关如何正确执行“自定义绘画”的部分以及有关键绑定的部分。

标签: java swing key-bindings key-events


【解决方案1】:

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

例如...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 2014-07-11
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    相关资源
    最近更新 更多