我的应用程序中有一个按钮。单击它会产生与按某个键完全相同的操作。所以我希望如果用户按下该键,按钮看起来就像被单击一样,即短暂变暗,然后再次恢复正常。因此,在我的 key 处理程序中我写道:
myButton.fire();
这会导致操作事件被触发,但按钮看起来不会被单击。我怎样才能实现后者?
最佳答案
您可以使用 myButton.arm(...)
和 myButton.disarm()
来“释放”它。
由于您可能希望它显示为按下一段时间,然后显示为松开,因此您需要遵循以下几行:
myButton.arm();
PauseTransition pause = new PauseTransition(Duration.seconds(0.5));
pause.setOnFinished(e -> myButton.disarm());
pause.play();
如果您想在释放时实际触发事件,请在调用 disarm()
时调用 myButton.fire()
:
pause.setOnFinished(e -> {
myButton.disarm();
myButton.fire();
});
这是一个 SSCCE。如果您按“向上”键(即向上光标键),它会模拟按下按钮:
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.PauseTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;
public class PrgorammaticallyPressButton extends Application {
@Override
public void start(Stage primaryStage) {
IntegerProperty count = new SimpleIntegerProperty();
Label label = new Label();
label.textProperty().bind(count.asString("Count: %d"));
Button button = new Button("Increment");
button.setOnAction(e -> count.set(count.get()+1));
VBox root = new VBox(5, label, button);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 350, 150);
scene.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
if (e.getCode() == KeyCode.UP) {
button.arm();
PauseTransition pause = new PauseTransition(Duration.seconds(0.5));
pause.setOnFinished(evt -> {
button.disarm();
button.fire();
});
pause.play();
}
});
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
关于JavaFX:使按钮看起来像被单击一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34978902/