例如,如果我想记录我按下了b键并想记录按住它的时间长度,我该怎么做?
答案 0 :(得分:2)
加工超级简单。请查看keyPressed()和keyReleased()。
// create a variable to store the time
int t = 0;
void setup() {
// whatever you need to do here
}
void draw() {
// do other stuff here
}
// when 'b' key is pressed, store the current
// time in milliseconds since the program started
void keyPressed() {
if (key == 'b') {
t = millis();
}
}
// when the 'b' key is released, subtract the start
// time from the current time to get the duration
void keyReleased() {
if (key == 'b') {
t = millis() - t;
println("b key held for " + t + " milliseconds");
}
}
答案 1 :(得分:1)
这是可能的方法之一:
import java.util.HashMap;
import java.util.Map;
import processing.core.PApplet;
import processing.event.KeyEvent;
// this map holds currently pressed keys
private Map<Character, Record> map = new HashMap<Character, Record>();
public void setup() {
...
}
public void draw() {
...
}
@Override
public void keyPressed(KeyEvent event) {
char key = event.getKey();
// only if map doesn't hold this key yet
if (!map.containsKey(key)) {
// create new record with this key and start timestamp
Record record = new Record(key, millis());
map.put(key, record);
}
}
@Override
public void keyReleased(KeyEvent event) {
char key = event.getKey();
// retrieve record for this key
Record record = map.get(key);
// store release timestamp (milliseconds from program startup)
record.releaseTime = millis();
map.remove(key);
// now record has full info
println(key + ", time: " + (record.releaseTime - record.pressedTime));
}
class Record {
char key;
long pressedTime;
long releaseTime;
Record(char key, long pressedTime) {
this.key = key;
this.pressedTime = pressedTime;
}
}
希望这会有所帮助......