【问题标题】:Getting input from keyboard using Scanner with JavaFX Stage使用带有 JavaFX Stage 的 Scanner 从键盘获取输入
【发布时间】:2013-10-26 15:36:33
【问题描述】:

我的申请有问题。当我打开我的应用程序以输入我的 xAxis 变量时,我必须专注于我的“终端”。

我希望当我专注于舞台时,我仍然可以键入我的变量。

(我强调的地方是我必须关注的地方) 问题截图:http://i.imgur.com/hKqMjoa.png(我没有足够的声望来发截图)

“没有响应”的一些帮助可能会有所帮助,但这不会对程序产生太大影响。

代码如下:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gamefx;

import java.util.Scanner;
import javafx.animation.Animation;
import javafx.animation.AnimationTimer;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class GameFX extends Application { 

public Image img = new Image("Block1.png");
public ImageView image = new ImageView(img);
public int yAxis = -300;
public int xAxis = 0;
public TranslateTransition  tt = new TranslateTransition(Duration.millis(5000), image);
public Scanner sn = new Scanner(System.in);
public String ifelse;

public void spriteAnimation(){
tt.setByY(yAxis);
tt.setCycleCount(1);
tt.play();  
}
public void getMove(){

ifelse = sn.nextLine();
switch (ifelse) {
    case "d":
        rightMove();
        System.out.print("Move Right");
        break;
    case "a":
        leftMove();
        System.out.print("Move left");
        break;
}

}

public int leftMove(){
xAxis = -100;
return xAxis;

}
public int rightMove(){
xAxis = 100;
return xAxis;
}
@Override
public void start(Stage primaryStage) throws InterruptedException{
    primaryStage.setTitle("Game");

    StackPane stckp1 = new StackPane();
    Scene scn = new Scene(stckp1, 700, 700);

    primaryStage.show();
    getMove();
    stckp1.getChildren().add(image);
    image.setTranslateX(xAxis);
    spriteAnimation();
    primaryStage.setScene(scn);



}

}

【问题讨论】:

    标签: java image variables javafx stage


    【解决方案1】:

    scanner.nextLine() 的调用将阻止您的整个应用程序,直到您按回车键。

    像 JavaFX 这样的小部件库提供 event handling mechanisms 用于处理键盘输入:

        scn.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if (event.getCode() == KeyCode.D) {
                    System.out.print("Move Right");
                } else if (event.getCode() == KeyCode.A) {
                    System.out.print("Move left");
                }
                event.consume();
            }
        });
    

    【讨论】:

    • 谢谢,我应该做更多的研究,我从没想过使用 EventHandler。
    猜你喜欢
    • 1970-01-01
    • 2013-07-06
    • 2011-10-19
    • 2010-11-29
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多