gpt4 book ai didi

java - 在 JavaFX 中同时按下按键

转载 作者:行者123 更新时间:2023-11-30 06:36:38 24 4
gpt4 key购买 nike

package javafx_pressing_simultaneous_keys;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;

public class JavaFX_Pressing_Simultaneous_Keys extends Application
{
final BooleanProperty ZPressed = new SimpleBooleanProperty(false);
final BooleanProperty XPressed = new SimpleBooleanProperty(false);
final BooleanBinding ZAndXPressed = ZPressed.and(XPressed);
int i = 0;

@Override
public void start(Stage stage)
{
BorderPane bp = new BorderPane();
bp.setStyle("-fx-background-color: linear-gradient(from 25% 25% to 100% 100%, #DC143C, #661A33)");
Scene s = new Scene(bp, 340, 300);

Label l1 = new Label();
l1.setFont(new Font("Arial", 56));
l1.setTextFill(Color.CADETBLUE);
bp.setCenter(l1);
l1.setText(Integer.toString(i));

// How to Respond to both Keys ("Z" and "X") pressed together.
ZAndXPressed.addListener(new ChangeListener<Boolean>()
{
@Override
public void changed(ObservableValue<? extends Boolean> obs, Boolean werePressed, Boolean arePressed)
{
i++;
l1.setText(Integer.toString(i));
}
});

s.setOnKeyPressed(new EventHandler<KeyEvent>()
{
@Override
public void handle(KeyEvent ke)
{
if (ke.getCode() == KeyCode.Z)
ZPressed.set(true);
else
if (ke.getCode() == KeyCode.X)
XPressed.set(true);
}
});

s.setOnKeyReleased(new EventHandler<KeyEvent>()
{
@Override
public void handle(KeyEvent ke)
{
if (ke.getCode() == KeyCode.Z)
ZPressed.set(false);
else
if (ke.getCode() == KeyCode.X)
XPressed.set(false);
}
});

stage.setScene(s);
stage.setTitle("JavaFX (Pressing Simultaneous Keys)");
stage.setResizable(false);
stage.show();
}


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

我试图编写一段代码,允许我同时按下 2 个键(例如 Z 和 X 键),然后计算我按下该组合键的次数。但我注意到每次我按 Z 和 X 键时程序都会计数两次。谁能告诉我这是正常的还是某些事件处理程序有问题?非常感谢。

最佳答案

ChangeListener 只知道其对象的状态已更改。它不知道它的对象如何或发生了什么。您现在的逻辑是每次 ZAndXPressed 更改时增加 i,无论是从 true 到 false,还是从 false 到 true。

试试这个:

// How to Respond to both Keys ("Z" and "X") pressed together.
ZAndXPressed.addListener(new ChangeListener<Boolean>()
{
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue)
{
if (newValue == true)
{
i++;
l1.setText(Integer.toString(i));
}
}
});

关于java - 在 JavaFX 中同时按下按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45112206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com