为什么孩子是空的? JavaFX的

时间:2014-07-01 22:38:07

标签: java javafx javafx-2 javafx-8

我有一个小的javaFX代码。 我想画画,但我有一些初学者的问题,我真的不太了解javaFX。

这是我的Main.java

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {
Controller controller;
    @Override
    public void start(Stage primaryStage) throws Exception{
        controller= new Controller();
        controller.Pane = FXMLLoader.load(getClass().getResource("sample.fxml"));
        System.out.printf("kk"+controller.canvas.isResizable());
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(controller.Pane, controller.Pane.getPrefWidth(), controller.Pane.getPrefHeight()));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

这是sample.FXML

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.canvas.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<AnchorPane fx:id="Pane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="284.0" prefWidth="484.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <children>
      <Canvas fx:id="canvas"  height="267.0" layoutX="13.0" layoutY="9.0" width="459.0" AnchorPane.bottomAnchor="8.0" AnchorPane.leftAnchor="13.0" AnchorPane.rightAnchor="12.0" AnchorPane.topAnchor="9.0" />
   </children>
</AnchorPane>

对于the controller.java,只有画布和窗格声明。

我的问题:

  1. Pane是父级,canvas是执行FXMLloader.load后的子级等,窗格不是null但是子方法在方法start中为null(外部像按钮的事件,子项不为null)为什么子项为null ? enter image description here
  2. 要使画布可调整大小,没有方法可以执行此类操作,唯一的解决方案是从Canvas扩展@Override方法isResizable使其成为true。但Canvas如果我这样做,我会从FXML得到它 Canvas MyCanvas= new CanvasResizable(); 这不工作我不知道为什么。 有没有像android这样的方式来制作例如canvas=(Canvas) findbyid(FXML.id.canvas);(类似的东西)
  3. 和我的上一个问题如何改变画布的颜色,没有办法做到这一点。

    我很抱歉,如果我的问题已经被一个不同的问题问到,为什么我在谷歌搜索了很多javaFX的文档。

1 个答案:

答案 0 :(得分:1)

不应直接创建FXML控制器。它将由FXMLLoader

为您初始化
public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception{
        FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
        Pane root = loader.load(); // controller was initialized
        controller = loader.getController();

        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, root.getPrefWidth(), root.getPrefHeight()));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

您可以在Oracle教程中找到更多详细信息:http://docs.oracle.com/javafx/2/fxml_get_started/fxml_tutorial_intermediate.htm#CACFEHBI

相关问题