首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >KeyListener JavaFX

KeyListener JavaFX
EN

Stack Overflow用户
提问于 2014-04-19 06:14:05
回答 2查看 28.3K关注 0票数 6

我在网上找了一下,但没有找到合适的信息。我正在尝试检测每次应用程序运行时的按键操作。我正在使用JavaFX,并用FXML运行它。我试了很多方法,但都不管用。请帮帮我。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-04-19 08:12:04

你应该去看看Ensemble sample。这是关键的监听器代码。

代码语言:javascript
复制
/**
 * Copyright (c) 2008, 2012 Oracle and/or its affiliates.
 * All rights reserved. Use is subject to license terms.
 */
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.PerspectiveTransform;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;

/**
 * A sample that demonstrates various key events and their usage. Type in the
 * text box to view the triggered events: key pressed, key typed and key 
 * released. Pressing the Shift, Ctrl, and Alt keys also trigger events.
 *
 * @see javafx.scene.input.KeyCode
 * @see javafx.scene.input.KeyEvent
 * @see javafx.event.EventHandler
 */
public class KeyEventsSample extends Application {

    private void init(Stage primaryStage) {
        Group root = new Group();
        primaryStage.setScene(new Scene(root));
        //create a console for logging key events
        final ListView<String> console = new ListView<String>(FXCollections.<String>observableArrayList());
        // listen on the console items and remove old ones when we get over 20 items in the list
        console.getItems().addListener(new ListChangeListener<String>() {
            @Override public void onChanged(Change<? extends String> change) {
                while (change.next()) {
                    if (change.getList().size() > 20) change.getList().remove(0);
                }
            }
        });
        // create text box for typing in
        final TextField textBox = new TextField();
        textBox.setPromptText("Write here");
        textBox.setStyle("-fx-font-size: 34;");
        //add a key listeners
        textBox.setOnKeyPressed(new EventHandler<KeyEvent>() {
            public void handle(KeyEvent ke) {
                console.getItems().add("Key Pressed: " + ke.getText());
            }
        });
        textBox.setOnKeyReleased(new EventHandler<KeyEvent>() {
            public void handle(KeyEvent ke) {
                console.getItems().add("Key Released: " + ke.getText());
            }
        });
        textBox.setOnKeyTyped(new EventHandler<KeyEvent>() {
            public void handle(KeyEvent ke) {
                String text = "Key Typed: " + ke.getCharacter();
                if (ke.isAltDown()) {
                    text += " , alt down";
                }
                if (ke.isControlDown()) {
                    text += " , ctrl down";
                }
                if (ke.isMetaDown()) {
                    text += " , meta down";
                }
                if (ke.isShiftDown()) {
                    text += " , shift down";
                }
                console.getItems().add(text);
            }
        });
        VBox vb = new VBox(10);
        vb.getChildren().addAll(textBox, console);
        root.getChildren().add(vb);
    }

    @Override public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.show();
    }
    public static void main(String[] args) { launch(args); }
}
票数 9
EN

Stack Overflow用户

发布于 2016-03-20 09:28:46

这对我很有效:

在FXML处,在元素中添加onKeyPressed属性。下面是一个示例,请注意AnchorPane元素中的onKeyPressed属性。

代码语言:javascript
复制
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" onKeyPressed="#handleKeyPressed"  xmlns:fx="http://javafx.com/fxml" fx:controller="com.jtetris.jtetris.FXMLController">
    <children>
        <Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
        <Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" />
    </children>
</AnchorPane>

接下来,在控制器中添加方法(handleKeyPressed

代码语言:javascript
复制
public class FXMLController implements Initializable {

  @FXML
  private Label label;

  @FXML
  private void handleButtonAction(ActionEvent event) {
      System.out.println("You clicked me!");
      label.setText("Hello World!");
  }

  @FXML
  private void handleKeyPressed(KeyEvent ke){
    System.out.println("Key Pressed: " + ke.getCode());
  }

  @Override
  public void initialize(URL url, ResourceBundle rb) {
    // TODO
  }
}

最后,在start方法中加载fxml。

代码语言:javascript
复制
public class MainApp extends Application {

 @Override
 public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));

    Scene scene = new Scene(root);

    stage.setTitle("JavaFX and Maven");
    stage.setScene(scene);
    stage.show();
 }
 public static void main(String[] args) {
    launch(args);
 }

}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23163189

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档