How to detect a key press in Java

前端 未结 6 1604
野的像风
野的像风 2020-12-30 07:29

My son (aged 11) who is learning Java is going to enter a question and some code. He tells me he has not been able to find the answer to this question on the site. You will

6条回答
  •  囚心锁ツ
    2020-12-30 08:17

    KeyListener

    You should be putting his KeyListener Event within the class you need it not in the Main Method!

    addKeyListener(new KeyListener() {
        public void keyPressed(KeyEvent e) {
            //This is where you want to implement your key!
            if(e.getKeyCode() == KeyEvent.VK_SPACE){
                 //Fire Gun!
            }
            ....
        }
    
        public void keyReleased(KeyEvent e) { //I dont really use these!
        }
    
        public void keyTyped(KeyEvent e) { //I dont really use these!
        }
    });
    

    More on Keys here: KeyListeners


    Public and Private:

    Now for Public and Private, there is already an answer on StackOVerflow which I think does the job pretty well! Here


    Functions/Methods and Void:

    As for Void, It is used in functions where you wish to return nothing! I do not know how well you know about functions but let me give you an example:

    int sum;
    public int addReturn(int x, int y){
        sum = x +y;
        return sum;
    }
    

    What this does is it adds the two ints given as x and y and then returns the sum as an integer!

    With void what you can do is:

    int sum;
    public void add(int x, int y){
        sum = x+ y;
    }
    

    Here you return nothing but it still stores x+y into sum!

    So in your class:

    int Summation, x = 10, y = 10;
    summation = addReturn(x,y); //<-- This will place summation = 10+10 = 20
    

    For the void function you do not need to make a variable since it doesnt return a value, rather it sets the value within the function. All you need to do is call it

    add(x,y);
    

    If you need more help just comment! :) Also I find it awesome that your son is so interested in Java at such a young age. Great Parenting :D

提交回复
热议问题