How to stop moving the slider until the key is released

class slider {
int y = 0;

  void draw() {
    keyPressed();
    keyReleased();
    //not going out of frame
    if(y < 0) y += 25;
    if(y > height-25) y -= 25;
    
    rect(width-30, y, 10, rectSize);
  }
  
  void keyPressed() {
      if (key == CODED) {
        if (keyCode == UP) {
          y = y - 10;
        } else if (keyCode == DOWN) {
          y = y + 10;
          } 
      } 
    }
  //void keyReleased() {
  //    if (key == CODED) {
  //      if (keyCode == UP) {
  //        y = y;
  //      } else if (keyCode == DOWN) {
  //        y = y;
  //        } 
  //    } 
  //  }
}

the slider is never stops in the direction.

you need to take keypressed() out of draw.
keyPressed is already bound to an event handler so does not need to be called in draw. It already runs in the background.

also keyPressed is a system function. So keep the code outside of the class otherwise you will have to add extra logic to release the keypress.

I need that logic I think…but I can’t figure out…

Then you either need another bit of code which makes use of the keyEvent listener, this will allow you to handle the logic without a crazy boolean scenario.

Alternatively and simpler yet, just use the keypressed method in the main sketch and pass the slider instance into keypressed.

void setup(){
  
};

// this loops unless noLoop() is called
void draw(){
  
}

//this does not loop but it triggered when key is pressed
void keyPressed(){
  //instead of placing keypressed in your class, add required code here
}

//this does not loop but is triggered when mouse is pressed
void mousePressed(){
  
}

class someClass{
  
  // if this is in draw it will keep looping
  void draw(){
    //keypressed will also keep looping
    keyPressed();
  };
  
  
  void keyPressed(){
    
  }
};

alternatively you can can create a class which handles keyEvents

package windowsGui;

import processing.core.PApplet;
import processing.event.KeyEvent;

public class KeyboardFunctions {
	PApplet p;

	public KeyboardFunctions() {

	};

	public void init(PApplet p) {
		this.p = p;
		p.registerMethod("keyEvent", this);  
	};
	

	public void destroy(){
		//destroys the registermethod or something like that 
	};

	public void keyEvent(final KeyEvent evt) {
		switch(evt.getAction()) {
		case KeyEvent.PRESS:
			keyPressed();
//			p.println(p.keyCode);
			//getKeyCode();
			break;
		case KeyEvent.RELEASE:
//			keyReleased();
			//getKeyCode();
			break;
		}
	};

	public void keyPressed() {

	};

	public void keyReleased() {
	};
};

Now your slider class can extend keyBoardfunctions and make use of keyEvent logic, meaning your code shouldnt loop anymore.

1 Like