是否可以在后台运行一个程序(例如JavaFX GUI),并使clickEvents保持活动状态?例如如果单击则播放声音 谢谢!
答案 0 :(得分:0)
您可以参考此答案How to detect mouseclick event outside the stage and close it
基本上,您需要向stage.focusedProperty()
注册一个侦听器,并在focus属性更改为false时调用函数。
修改后的代码
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class CloseWindowOnClickOutside extends Application {
@Override
public void start(Stage primaryStage) {
Button showPopup = new Button("Show popup");
showPopup.setOnAction(e -> {
Stage popup = new Stage();
Scene scene = new Scene(new Label("Popup"), 120, 40);
popup.setScene(scene);
popup.initModality(Modality.APPLICATION_MODAL);
popup.initOwner(primaryStage);
popup.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
//if the click is outside the stage
if (! isNowFocused) {
myFunction();
}
});
popup.show();
});
StackPane root = new StackPane(showPopup);
Scene scene = new Scene(root, 350, 120);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public void myFunction(){
//handle the event here
}
}