停止将文件选择器键事件传播到JavaFX中的(父)阶段

时间:2018-11-05 17:45:54

标签: javafx

我需要在舞台上聆听关键事件,但是在显示FileChooser时不需要。

当显示KeyEvent时,是否有办法停止Esc(例如,按下Stage键)传播到(父)FileChooser

OR

检测到KeyEvent是从FileChooser传播的吗?

class KeyEventTest extends Application
{
  @Override
  public void start(Stage stage) throws Exception
  {
    Button browseBtn = new Button("Browse File System");
    browseBtn.setOnAction(ae ->
      {
        FileChooser fileChooser = new FileChooser();
        fileChooser.showOpenMultipleDialog(stage);
      });

    stage.setScene(new Scene(new BorderPane(browseBtn), 500, 200));
    stage.setTitle("Test");

    stage.addEventHandler(KeyEvent.KEY_RELEASED, keyEvent ->
      {
        // Do not trigger when Esc key is pressed on FileChooser
        KeyCode keyCode = keyEvent.getCode();
        System.out.println(keyCode);
      });

    stage.centerOnScreen();
    stage.show();
  }

  public static void main(String[] args)
  {
    launch(args);
  }
}

1 个答案:

答案 0 :(得分:0)

有可能实现它。您是正确的,如果使用转义或ALT + F4关闭FileChooser,则事件将传播,但是您需要考虑哪个事件?如果您只看{strong> KeyEvent.KEY_RELEASED。因此,如果您只是在按下键时添加了事件过滤器记录,则可以在主阶段或FileChooser中找到按下转义符(或alt + f4)的时间

您或多或少都在尝试找出KEY_PRESSED是否由FileChooser处理。如果是这样,那么KEY_RELEASED也将从FileChooser中处理,否则我们将在主应用程序中触发KeyEvent。

这里是一个例子:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class Main extends Application {

    private boolean captureKeys = false;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        Button browseBtn = new Button("Browse File System");
        browseBtn.setOnAction(ae -> {
            captureKeys = false;
            FileChooser fileChooser = new FileChooser();
            fileChooser.showOpenMultipleDialog(stage);
        });

        stage.setScene(new Scene(new BorderPane(browseBtn), 500, 200));

        stage.addEventFilter(KeyEvent.KEY_PRESSED, keyEvent -> {
            captureKeys = true;
            // For debug
            // KeyCode keyCode = keyEvent.getCode();
            // System.out.println("KEY_PRESSED on Stage : " + keyCode);
        });

        stage.addEventHandler(KeyEvent.KEY_RELEASED, keyEvent -> {
            if(captureKeys) {
                KeyCode keyCode = keyEvent.getCode();
                System.out.println(keyCode);
            }
        });

        stage.centerOnScreen();
        stage.show();
    }
}