JavaFX使用Netbeans模板Javfx FML应用程序

时间:2015-08-10 10:53:58

标签: netbeans javafx fxmlloader

我认为这是一个非常愚蠢的问题,但我没有达到目的。如果您使用Java制作FXML-Template项目,则会自动获得三个文件。 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");
        }
   });
}    

}

1 个答案:

答案 0 :(得分:0)

我现在解决了。首先,我在Scene Builder中为根窗格提供了一个Code FX:ID为root的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();
            }
        }
    });