问题描述:

I thing it is a very silly question but I don't manage to to this. If you made a FXML-Template Project with Java, you got automatically three files. The view in XML, the controller and the start file in java.

I want to use the scene in the controller class but I don't know how to make a reference to do this.

Here is my example:

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;

}

}

public class FXMLDocumentController implements 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");

}

});

}

}

网友答案:

I solved it now. First I gave in the Scene Builder a Code FX:ID named root to the root pane. root is in the controller an object and I registered on root an 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();
            }
        }
    });
相关阅读:
Top