我检查了导入,并检查了ImageView的fx:id和在控制器类中给它的变量名是否匹配,但仍然无法正常工作。在该类的其他子例程中,按钮和标签等其他东西都可以正常工作,因此我不知道此ImageView有什么问题。
这是我的FXML文档:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/10.0.1" fx:controller="application.Controller">
<children>
<ImageView fx:id="body" fitHeight="150.0" fitWidth="200.0" layoutX="243.0" layoutY="100.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="@../img/BB8Body.png" />
</image>
</ImageView>
</children>
</AnchorPane>
这是控制器中不起作用的部分:
package application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
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.text.Text;
import javafx.stage.Stage;
public class Controller {
@FXML
public ImageView body = new ImageView();
public void level1(ActionEvent event) {
//changing scenes to level 1
Scene scene=null;
try {
Parent root = FXMLLoader.load(getClass().getResource("Level1.fxml"));
scene = new Scene(root);
Stage primaryStage=(Stage)((((Node) event.getSource()).getScene().getWindow()));
primaryStage.setScene(scene);
primaryStage.show();
initData();
//lev1=true;
} catch(Exception e) {
e.printStackTrace();
}
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
switch (event.getCode()) {
case UP:
body.setLayoutY(body.getLayoutY() - 5);
System.out.println("UP");
break;
case RIGHT:
body.setLayoutX(body.getLayoutX() + 5);
System.out.println("RIGHT");
break;
case DOWN:
body.setLayoutY(body.getLayoutY() + 5);
System.out.println("DOWN");
break;
case LEFT:
body.setLayoutX(body.getLayoutX() - 5);
System.out.println("LEFT");
break;
default:
break;
}
}
});
}