How does one properly handle keypresses and repainting of a JComponent in the context of moving a ball around a screen?

前端 未结 3 1344
执笔经年
执笔经年 2020-12-11 23:28

I thought I would try and write a program that would paint a ball, and when the arrow keys are pressed, would move the ball around the screen in the direction pressed. First

3条回答
  •  春和景丽
    2020-12-11 23:49

    It seems that you never initialized actionPress - try adding this to your BallComponent constructor:

    actionPress = new ActionPress();
    

    ie, your constructor would look like this

    public BallComponent()
    {
        super();
        super.setFocusable(true);
    
        InputMap imap1 = this.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        imap1.put(KeyStroke.getKeyStroke("ctrl Y"), "keyUp1");
        InputMap imap2 = this.getInputMap(JComponent.WHEN_FOCUSED);
        imap1.put(KeyStroke.getKeyStroke("ctrl Y"), "keyUp2");
        InputMap imap3 = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);   
        imap1.put(KeyStroke.getKeyStroke("ctrl Y"), "keyUp3");
    
        actionPress = new ActionPress();
        ActionMap amap = this.getActionMap();
        amap.put("keyUp1", actionPress);
        amap.put("keyUp2", actionPress);    
        amap.put("keyUp3", actionPress);
    }
    

提交回复
热议问题