How do I have multiple key inputs Listened to at the same time

后端 未结 2 969
你的背包
你的背包 2021-01-22 13:08

I\'m attempting to create a simple pong game in Java, but I don\'t know how to have both players using the keyboard at the same time. The game is incomplete and I\'m working on

2条回答
  •  温柔的废话
    2021-01-22 13:39

    Don't use a KeyListener. You should be using Key Bindings.

    See Motion Using the Keyboard for more information.

    I added the following code to the KeyboardAnimation example from the above link, which will allow you to do what you want:

    JLabel label2 = new JLabel( new ColorIcon(Color.GREEN, 40, 40) );
    label2.setSize( label2.getPreferredSize() );
    label2.setLocation(500, 500);
    contentPane.add( label2 );
    
    KeyboardAnimation animation2 = new KeyboardAnimation(label2, 24);
    animation2.addAction("A", -3,  0);
    animation2.addAction("D", 3,  0);
    animation2.addAction("W",    0, -3);
    animation2.addAction("S",  0,  3);
    

提交回复
热议问题