【问题标题】:Javafx imageView rotation when key pressed按下键时Javafx imageView旋转
【发布时间】:2017-03-28 17:27:30
【问题描述】:

基本上,当用户在键盘上按 R 键时,我想将 ImageView 旋转 90 度。

@FXML
private Image arrow;
@FXML
private ImageView arrowDirection;


@FXML
public void arrowRotation(KeyEvent keyEvent)
{
    if(keyEvent.getCode() == KeyCode.R)
    arrowDirection.setRotate(90);
}

【问题讨论】:

    标签: java javafx imageview keyevent


    【解决方案1】:

    你的问题有点不具体,所以我假设你想要一个 EventHandler 被添加到图像视图所在的窗格中,并且你想要在 Controller 中设置它。这是我的解决方案:

    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);
                }
            });
    
        }    
    
    }
    

    当然,这需要一个在 Pane 内保存 ImageView 的 FXML,但可以轻松调整以适应您的需求。 执行旋转的函数与您想象的非常相似,但我会尽可能使用 equals 进行比较。我在窗格的 sceneProperty 中添加了一个侦听器,以便在加载整个内容并设置场景后让窗格请求焦点。这意味着按下一个键实际上会触发在窗格中注册的 KeyEventHandler。注册 EventHandler 再次简单明了。希望有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多