Reputation: 3
Basically, I want to rotate an ImageView by 90 degrees when the user hits R on the keyboard.
@FXML
private Image arrow;
@FXML
private ImageView arrowDirection;
@FXML
public void arrowRotation(KeyEvent keyEvent)
{
if(keyEvent.getCode() == KeyCode.R)
arrowDirection.setRotate(90);
}
Upvotes: 0
Views: 897
Reputation: 415
Your question is a bit unspecific, so I assumed that you want an EventHandler that is added to the pane in which the image view rests, and that you want to set it in the Controller. This is my solution:
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Pane;
public class FXMLDocumentController implements Initializable {
@FXML
Pane pane;
@FXML
ImageView imgView;
public void arrowRotation(KeyEvent event){
if(event.getCode().equals(KeyCode.R))
imgView.setRotate(90);
}
@Override
public void initialize(URL url, ResourceBundle rb) {
Image img = new Image("https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/Javafx-layout-classes.svg/1000px-Javafx-layout-classes.svg.png");
imgView.setImage(img);
pane.sceneProperty().addListener(new ChangeListener<Scene>() {
@Override
public void changed(ObservableValue<? extends Scene> observable, Scene oldValue, Scene newValue) {
if(newValue != null){
pane.requestFocus();
}
}
});
pane.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
arrowRotation(event);
}
});
}
}
Of course, this needs an FXML that holds an ImageView inside of a Pane, but that can easily be adjusted to fit your needs. The function that performs the rotation works pretty much like you thought, but I would compare using equals whenever possible. I added a listener to the sceneProperty of the pane to let the pane request the focus once the whole thing is loaded and the scene is set. This means that pressing a key will actually trigger KeyEventHandlers that are registered on the pane. Registering the EventHandler is straight forward again. Hope that helps :)
Upvotes: 1