0

我认为这是一个非常愚蠢的问题,但我无法做到这一点。如果您使用 Java 制作了 FXML 模板项目,您会自动获得三个文件。XML 中的视图、控制器和 java 中的启动文件。我想在控制器类中使用场景,但我不知道如何引用来执行此操作。这是我的例子:

public class CatchTheScene extends Application {
private Scene scene;
private Parent root;



@Override
public void start(Stage stage) throws Exception {
    root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
    FXMLDocumentController controller = new FXMLDocumentController(this);
    scene = new Scene(root);

    stage.setScene(scene);
    stage.show();
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

/**
 * @return the scene
 */
public Scene getScene() {
    return scene;
}

/**
 * @param scene the scene to set
 */
public void setScene(Scene scene) {
    this.scene = scene;
}

}

公共类 FXMLDocumentController 实现 Initializable {

private CatchTheScene c; 
@FXML
private Label label;
@FXML
private Button button;
@FXML
private AnchorPane root;

@FXML
private void handleButtonAction(ActionEvent event) {
    System.out.println("You clicked me!");
    label.setText("Hello World!");
}

public FXMLDocumentController(CatchTheScene c)
{
    this.c = c; 
}

@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO
    c.getScene().addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>(){

        @Override
        public void handle(MouseEvent event) {
           System.out.println("I am the scene and have been clicked");
        }
   });
}    

}

4

1 回答 1

0

我现在解决了。首先,我在 Scene Builder 中为根窗格提供了一个名为 root 的 Code FX:ID。root 在控制器中是一个对象,我在 root 上注册了一个 EventListener。`

@FXML
private Canvas canvas;
@FXML
private AnchorPane root;

root.setOnKeyPressed(new EventHandler<KeyEvent>() {

        @Override
        public void handle(KeyEvent e) {
            if (e.getCode() == KeyCode.LEFT) {

                clownfish.setDx(-10);
                clownfish.moveLeft();
            }
            if (e.getCode() == KeyCode.RIGHT) {

                clownfish.setDx(-10);
                clownfish.moveRight();
            }

            if (e.getCode() == KeyCode.UP) {

                clownfish.setDy(-10);
                clownfish.moveUp();
            }
            if (e.getCode() == KeyCode.DOWN) {

                clownfish.setDy(-10);
                clownfish.moveDown();
            }
        }
    });
于 2015-08-10T12:24:10.993 回答