我有一个小的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
,只有画布和窗格声明 .
我的问题 :
-
窗格是父级,画布是做完FXMLloader.load等后的子窗格,窗格不是null但是子窗口方法启动时为null(外部像按钮的事件,子窗口不是null)为什么子窗口为空?
-
为了使画布可调整大小,没有方法可以做这样的事情,唯一的解决方案是从
Canvas
和@Override
方法扩展isResizable
使其成为true
. 但Canvas
如果我这样做的话,我会从FXML得到它't work I don'这知道为什么 . 有没有像android这样的方式来制作例如canvas=(Canvas) findbyid(FXML.id.canvas);
(类似的东西)
我的最后一个问题是如何改变画布的颜色,没有办法做到这一点 .
我很抱歉,如果我的问题已经被一个不同的问题问到,为什么我在谷歌搜索了这么多,缺乏javaFX的文档 .
1 回答
不应直接创建FXML控制器 . 它将由
FXMLLoader
为您初始化:您可以在Oracle教程中找到更多详细信息:http://docs.oracle.com/javafx/2/fxml_get_started/fxml_tutorial_intermediate.htm#CACFEHBI