【问题标题】:Need to increment by 1 every time key is pressed-JavaFx每次按键都需要加1-JavaFx
【发布时间】:2016-12-07 05:36:19
【问题描述】:

每次我按下一个键,在这种情况下,我需要我的 p1Start 值,在这种情况下 p1StartX 增加 1。这用于在矩形类型的二维数组中“绘制”路径。

我的问题是,它只增加一次。我该如何解决这个问题?

 scene2.setOnKeyPressed(e -> {
        int p1StartX = 5;
        int p1StartY = 25;
        int p2StartX = 60;
        int p2StartY = 25;

        if (e.getCode() == KeyCode.LEFT) {
            p1.setDirection(1);
            p1.update();
        } else if (e.getCode() == KeyCode.RIGHT) {
            p1StartX++;
            gameGrid[p1StartY][p1StartX].setFill(p1.getPlayerClr());

            System.out.println("Player 1: Right");

        }

【问题讨论】:

    标签: java javafx draw increment


    【解决方案1】:

    这是因为p1StartX 是在您的侦听器范围内定义的。

    将其移至类成员(静态或非静态 - 取决于您的设计...) - 一切都会好起来的。

    此外,我很确定这适用于您定义的所有 int 值。

    像这样:

    //some class definition...
    private int p1StartX;
    
    //Use a constructor to init the value of p1StartX.
    
    ...
    
    scene2.setOnKeyPressed(e -> {
    
        ....
    
            p1StartX++;
    
        }
    

    【讨论】:

    • 谢谢你,我用我的其他类创建了一个增量器,每次按下它都会起作用,我会永远爱你!
    猜你喜欢
    • 1970-01-01
    • 2021-02-24
    • 2021-07-19
    • 2020-10-25
    • 2020-09-25
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多