Question: JavaFX: Change CSS PseudoClass on Key Event

Question

JavaFX: Change CSS PseudoClass on Key Event

Answers 1
Added at 2017-01-01 00:01
Tags
Question

I have a button which changes it`s design when it is clicked. (Per CSS) Easy.

But I also want to enable the function that if you press ENTER it should also be pressed. That works, but I have a pseudo-class which sets the size of the button to 90% (.button:pressed).

Problem: It doesn't work when the Enter key is pressed. The click works fine. Is there any css pseudo-class for KeyTyped?

CSS:

.button{
        -fx-background-image: url("../resources/Game/cookie.png");
        -fx-background-color: transparent;
}

.button:pressed{
    -fx-background-size: 90%;
    -fx-background-position: center;
}

Thank you in advance :)

Answers
nr: #1 dodano: 2017-01-01 21:01

You can explicitly add the pseudo-class "pressed" when Enter is pressed and then remove it when it is released.

button.setOnKeyPressed(e -> {
   if (e.getCode() == KeyCode.ENTER) {
      button.pseudoClassStateChanged(PseudoClass.getPseudoClass("pressed"), true);
   }
});

button.setOnKeyReleased(e -> {
   if (e.getCode() == KeyCode.ENTER) {
      button.pseudoClassStateChanged(PseudoClass.getPseudoClass("pressed"), false);
   }
});

MCVE

import javafx.application.Application;
import javafx.css.PseudoClass;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Test extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Button button = new Button("Change Color");
        button.setOnKeyPressed(e -> {
            if (e.getCode() == KeyCode.ENTER) {
                button.pseudoClassStateChanged(PseudoClass.getPseudoClass("pressed"), true);
            }
        });

        button.setOnKeyReleased(e -> {
            if (e.getCode() == KeyCode.ENTER) {
                button.pseudoClassStateChanged(PseudoClass.getPseudoClass("pressed"), false);
            }
        });
        StackPane stackPane = new StackPane(button);
        Scene scene = new Scene(stackPane, 200, 200);
        scene.getStylesheets().add(getClass().getResource("test.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

test.css

.button:pressed{
    -fx-background-color: red;
}
Source Show
◀ Wstecz