在我的程序中,我需要在按按钮长/单击按钮时进行操作。因此,我决定创建一种方法,该方法在其参数中获取按钮,并在单击按钮超过1秒时返回布尔值:
public class EventOperations {
JFXButton button;
boolean result = false;
// Button long click
public EventOperations(JFXButton btn) {
button = btn;
}
public void isLongPressed() {
final AnimationTimer timer = new AnimationTimer() {
private long lastUpdate = 0;
@Override
public void handle(long time) {
if (this.lastUpdate > 2000000000) {
result = true;
System.out.println("PRESSED !!!!!!!!!");
}
this.lastUpdate = time;
}
};
button.addEventFilter(MouseEvent.ANY, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getEventType().equals(MouseEvent.MOUSE_PRESSED)) {
timer.start();
} else {
timer.stop();
}
}
});
}
public boolean getIsPressed() {
return result;
}
}
main.java
EventOperations buttonPressed = new EventOperations(jfxButtonFolder);
buttonPressed.isLongPressed();
但是,每当我在按钮上快速单击时,都会显示几个"按下!!!"所以它不起作用。20000000的数量就是一个示例。我该怎么做才能在我的主要Java方法中获得布尔值,如果"按"调用函数来做某事?
编辑!这是完美的工作,谢谢!
只需使用开始和结束时间:
button.addEventFilter(MouseEvent.ANY, new EventHandler<MouseEvent>() {
long startTime;
@Override
public void handle(MouseEvent event) {
if (event.getEventType().equals(MouseEvent.MOUSE_PRESSED)) {
startTime = System.currentTimeMillis();
} else if (event.getEventType().equals(MouseEvent.MOUSE_RELEASED)) {
if (System.currentTimeMillis() - startTime > 2 * 1000) {
System.out.println("Pressed for at least 2 seconds (" + (System.currentTimeMillis() - startTime) + " milliseconds)");
} else
System.out.println("Pressed for " + (System.currentTimeMillis() - startTime) + " milliseconds");
}
}
});
animationTimer中 handle
方法的 time
参数是纳米秒中当前帧的 timestamp 。因此,您不应将lastUpdate
设置为此值,并将其与所需的鼠标保持间隔进行比较。
在参数lastUpdate
中单击鼠标时,您应该记录时间戳,并且handle
事件应检查当前时间和lastUpdate
之间的差异,以查看它是否大于您的鼠标保持间隔。
结果代码看起来像这样:
public void isLongPressed() {
final AnimationTimer timer = new AnimationTimer() {
private long lastUpdate = 0;
@Override
public void handle(long time) {
if (Instant.now() - lastUpdate > 2000000000) {
result = true;
System.out.println("PRESSED !!!!!!!!!");
}
stop();
}
@Override
public void start() {
super.start();
lastUpdate = Instant.now(); // Assuming you are using Java 9
}
};
button.addEventFilter(MouseEvent.ANY, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getEventType().equals(MouseEvent.MOUSE_PRESSED)) {
timer.start();
} else {
timer.stop();
}
}
});
}