Search code examples
javabuttonlwjgl

Custom button is being executed 3-4 times on click


I made a simple button class (using lwjgl to render rectangle), however when i click the button, the code that's supposed to run when clicked is executed 1-5 times.

Here's method from button class:

public boolean clicked(float mX, float mY){
    if(mX >= x && mX <= x + width && 
            mY <= Display.getHeight() - y && mY >= Display.getHeight() - (y + height)){
        return true;
    }else{
        return false;
    }
}

Here's the code in the class that utilizes the button class and method:

public void getInput(){
    if(Mouse.next()){
        if(Mouse.isButtonDown(0)){
            if(b.clicked(Mouse.getX(), Mouse.getY())){
                System.out.println("button clicked");
            }
        }
    }
}

Thanks!


Solution

  • The solution is very simple: you have to us Mouse.isButtonDown is called if your mousebutton is down. So if you press your mouse for 1 second it would call this method about 50 times(determine on the tickrate of your Program). You have to use a boolean wich store the state at the last tick. This could look like this:

    boolean prevState;
    public void update(...){
        if(Mouse.isButtonDown(0) && !prevState){
            item++;
        }
        prevState = Mouse.isButtonDown(0);
    }
    

    If you have a question i will try to answer it :)