Search code examples
javaloopsif-statementlibgdxbreak

Breaking If statements.. Clicking a button once


I am trying to make a keyboard and everything works fine. I just want to break the if statement after each click to stop repetitiveness of the char. I don't want to use a Boolean because user can enter same character more than once. This is the image listener

 a = new Image(new Texture("Sprites/Keyboard/a.png"));
    a.addListener(new InputListener(){
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

            apressed = true;
            return true;
        }

        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {

            apressed= false;

        }

    });

And this is what i have in my update inside the activity or state.

 @Override
 public void handleInput() {

   if (keyboard.apressed) {

            builder.append('A');
            currentWord = builder.toString();
            //break; here doesn't work. says its outside the loop.

        }
 }

So in theory this is what i want but can't use because im guessing its to much work for every char?

 @Override
 public void handleInput() {

 if (keyboard.apressed) {

            builder.append('A');
            currentWord = builder.toString();
            try {
                TimeUnit.MILLISECONDS.sleep(400);

            } catch (Exception e) {
                System.out.println("error");
            }
        }

any ideas? thanks in advance.


Solution

  • I made my own keyboard as well using LibGDX TextButtons. Since you are using images and not text, you could use the ImageButton instead. I then used the ChangeListener with the changed() method because it only triggers after pressing and releasing the button, which avoids repetitive characters while the button is being pressed.

    keyButton.addCaptureListener(new ChangeListener() {
    @Override
        public void changed(ChangeEvent event, Actor actor){
            // key logic here