Domanda

So I'm just learning java, and from my work in C++, key dectection was much easier with SDL. But when I try to do it in Java it never seems to work. Could someone please check my code and make sure all of this is alright? And yes I did import everything....

public class start extends JFrame{
JLabel label = new JLabel();
Screen circle = new Screen();
int x = 0;
int y = 0;
static boolean m = false;
boolean running = true;

public static void main(String args[]){
    start gui = new start();
    gui.go();

}

public void go(){
    JFrame j = new JFrame();
    j.setDefaultCloseOperation(EXIT_ON_CLOSE);
    j.setSize(400,400);
    pannel p = new pannel();
    Player player = new Player();
    j.add(player);



    j.setVisible(true);

    player.addKeyListener(new key());

    //try{
    //  for(int i = 0; i < 300; i ++){
    //      player.update();
    //      Thread.sleep(50);
    //      j.repaint();
    //  }
    //}
    //catch(Exception e){}

This try block was me testing to make sure that player.update() worked.... which it did! So I know the problem isn't with the update function

    while(running){
        //Updates
        if(m)
            player.update();
        System.out.println(m);

I have the program printing out the value of m to see if its ever true... which it never is...

        //Rendering

        player.repaint();

    }

}

public class pannel extends JPanel{
    public void pannel(){
        JPanel p = new JPanel();
        Player player = new Player();

        p.add(player);

        p.setVisible(true);


    }
}

public class key implements KeyListener{

    public void keyPressed(KeyEvent e) {
        switch(e.getKeyCode()){
        case KeyEvent.VK_SPACE:
            m = true;
            break;
        }

    }

    public void keyReleased(KeyEvent e) {
        switch(e.getKeyCode()){
        case KeyEvent.VK_SPACE:
            m = false;
            break;
        }

    }

    public void keyTyped(KeyEvent e) {

    }

}

}

In C++ there was a function that you had to call in order to detect if there has been any sort of key detection. You used this function in the main loop and it was really easy... Is there a function like this for Java? Or do I really need to put a key listener on EVERY object that I want to be effected by that key?

È stato utile?

Soluzione

The simplest solution, and generally the more powerful, would be to use the key bindings API

The main problem with KeyListener is that is focus contextual. That is, the component it is registered to must be focusable AND have focus before it will raise key events

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top