Как определить, запускается ли Mnemonic / KeyCombination для элемента управления? - PullRequest
0 голосов
/ 07 июня 2018

Я хотел бы знать, как я могу определить, запускается ли KeyCombination (созданная с помощью Mnemonic) для элемента управления.Или, для простоты, метод обработчика для Mnemonics?

По сути, я работаю с пользовательским элементом управления, который расширяется от Labeled и его Behavior класса, я хочуВыполните некоторые дополнительные действия, когда назначенный Mnemonic сработает.


EDIT

Так что после небольшого копания у меня возникла идея просто прослушать KeyEvent изScene (но учтите, что это ПРОСТО ИДЕЯ. В любом случае, остальное я выясню позже).Вот как это сделать:

public CustomLabeledBehavior(CustomLabeled control) {
  super(control, ...);

  /* IMPORTANT PART */
  // Assume that mnemonicParsing is set to true
  TextBinding tb = new TextBinding(control.getText());
  KeyCombination kc = tb.getMnemonicKeyCombination();

  control.getScene().addEventFilter(KeyEvent.KEY_PRESSED, e -> {
    if (kc.match(e)) {
      System.out.println("MATCHED!");
    }
  });
}

1 Ответ

0 голосов
/ 07 июня 2018

ОБНОВЛЕНИЕ

Чтобы сделать этот ответ более полезным, чем раньше, я покажу вам метод, который я использую в настоящее время, чтобы определить, запущен ли KeyCombination.Поэтому я постараюсь объяснить каждую деталь, если смогу.

Мы сосредоточены только на добавлении Mnemonic, используя свойство MnemonicParsing пользовательского элемента управления.И мы назовем этот пользовательский элемент управления как CustomLabeled, поскольку, основываясь на этом вопросе, он расширяется от класса Labeled, следовательно, его название основано на нем.Тогда мы будем работать внутри класса Skin, называемого CustomLabeledSkin.

# 1 Инициализация элемента управления:

<!-- Assuming that this FXML is already set and is attached to a Scene -->
<CustomLabeled text="_Hello World!" mnemonicParsing="true"/>

# 2 Настройка нашего MnemonicHandler:

/* These two variables are initialized from the Constructor. */
private KeyCombination kb; // The combination of keys basically, ALT + Shortcut key
private String shortcut; // The shortcut key itself basically, a Letter key

private boolean altDown = false; // Indicator if the user press ALT key

/**
 * This handler is a convenience variable to easily attach
 * and detach to the Scene's event handlers. This is the
 * whole idea to determine whether the KeyCombination is
 * triggered.
 */
private EventHandler<KeyEvent> mnemonicHandler = new EventHandler<KeyEvent>() {
  @Override
  public void handle(KeyEvent event) {
    // The KeyCombination, basically, the ALT + Shortcut key.
    if (kb.match(event) {
      // TODO: Execute command here.
      event.consume(); // Prevent from further propagation.
      return; // Make sure that the rest won't be executed.
    }
    // While these two functions are for separate event.
    // Example, pressing ALT first before the Shortcut key.
    if (event.isAltDown()) altDown = !altDown;
    if (altDown && event.getCode() == KeyCode.getKeyCode(shortcut)) {
      // TODO: Execute command here.
      event.consume();
    }
  }
}

# 3 Инициализация нашего класса кожи:

/**
 * Constructor
 */
public CustomLabeledSkin(CustomLabeled control) {
  // Since this is just an example/testing, we will only assume
  // that MnemonicParsing is enabled and a valid Mnemonic is
  // registered. So if you want to validate a mnemonic, you
  // might want to do it here.
  TextBinding tb = new TextBinding(control.getText());
  kc = tb.getMnemonicKeyCombination();
  shortcut = tb.getMnemonic();

  // Then we can just filter for a KEY_PRESS from the Scene, then
  // everything else will be handled by our MnemonicHandler.
  control.getScene().addEventFilter(KeyEvent.KEY_PRESSED, mnemonicHandler);
}

ПРИМЕЧАНИЕ: Класс TextBinding не является частью общедоступного API, он используется узлом Labeled для обработки мнемоники.

Более того, вы можете создать метод для отсоединения MnemonicHandlerесли в данный момент нет назначенной мнемоники (например, ранее была мнемоника, то код был изменен ...).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...