简体   繁体   English

Java keyListener在BasicConstruct上不起作用

[英]Java keyListener not working on BasicConstruct

I am testing some things with j3d and i cant seem to get a keylistener to work for a BasicConstruct. 我正在用j3d测试某些东西,但似乎无法让Keylistener为BasicConstruct工作。 It isn't doing anything when i press ay of the 38 key (up), not even the debug output to console. 当我按38键(向上)时,它什么也没做,甚至没有调试输出到控制台。 heres part of my main class "BasicConstruct". 这是我的主类“ BasicConstruct”的一部分。 here is where it should be registering: 这是应该注册的地方:

@SuppressWarnings("deprecation")  //for the bc.show(true);
public static void main(String[] argv) {
    bc = new BasicConstruct();

    bc.setTitle("3D Rendering");

    bc.setSize(500, 500);
    bc.setLocationRelativeTo(null);
    bc.setDefaultCloseOperation(EXIT_ON_CLOSE);
    bc.refresh(addBox(0f, 0f, 0f, 0.005f, 0.5f, 0.5f, 
        new Color3f(1, 0, 0), new Color3f(1, 0, 0)));  //draws a box on screen. not relevant to the queston

    bc.setFocusable(true);
    bc.addKeyListener(new PopClickListener());

    bc.addDirectionalLight(new Vector3f(0f, 0f, -1f), new Color3f(1f, 1f, 0f));
    bc.finalise(rootBranchGroup);
    bc.show(true);
}

and the PopClickListener class (havent bothered to rename it): 和PopClickListener类(需要重新命名):

import java.applet.Applet;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
import javax.vecmath.Color3f;
public class PopClickListener extends Applet implements KeyListener {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == 38){
            BasicConstruct.placeblockonscreen(BasicConstruct.bc, randInt(.1f, 0f),
                randInt(1f, 0f), randInt(.1f, 0f), randInt(.1f, 0f), randInt(.1f, 0f),
                randInt(.1f, 0f), new Color3f(10, 10, 10), new Color3f(10, 10, 10));
                System.out.println("hey"); //debug
        }
    }
    public void keyReleased(KeyEvent e) {}
    public void keyTyped(KeyEvent e) {}

    public static float randInt(float min, float max) {

        Random rand = new Random();

        float finalfloat = rand.nextFloat() * (max - min) + min;

        return finalfloat;
    }
}

Well first of all, make sure that the keyPressed() is getting called by placing a System.out.println("KEY PRESSED"); 首先,通过放置System.out.println("KEY PRESSED");确保keyPressed()被调用System.out.println("KEY PRESSED"); outside the if statement, but still inside the method. 在if语句之外,但仍在方法内部。 If that works, change the code so that it displays the key character, the key code, and some other things about the KeyEvent. 如果可行,请更改代码,使其显示键字符,键代码以及有关KeyEvent的其他内容。 This will tell you which key is being pressed. 这将告诉您正在按下哪个键。 Finally, I suggest using KeyEvent.VK_UP instead of the integer 38 to insure expected results. 最后,我建议使用KeyEvent.VK_UP而不是整数38来确保预期结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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