代码之家  ›  专栏  ›  技术社区  ›  lapots

在代码中将组件添加到fxml

  •  0
  • lapots  · 技术社区  · 7 年前

    我有一个fxml模板

    <VBox fx:id="playerAvatarBox" prefHeight="406.0" prefWidth="303.0" 
          xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.lapots.breed.editor.fx.controls.controller.CanvasDrawingController">
        <children>
            <Label text="Current representation" />
          <HBox prefHeight="24.0" prefWidth="303.0">
             <children>
                <ComboBox fx:id="layersBox" prefWidth="150.0" />
                <Button fx:id="addLayer" mnemonicParsing="false" onAction="#handleAddLayer" text="Add layer" />
             </children>
          </HBox>
          <Pane fx:id="canvasPane" prefHeight="369.0" prefWidth="303.0" />
        </children>
        <padding>
            <Insets top="5.0" />
        </padding>
    </VBox>
    

    我想添加一个 canvas pane 具有 fx:id=canvasPane . 在我的 controller 我是这样做的

    public class CanvasDrawingController implements Initializable {
        @FXML
        private Pane canvasPane;
    
        @Override
        public void initialize(URL location, ResourceBundle resources) {
            Canvas backgroundLayer = new Canvas(canvasPane.getWidth(), canvasPane.getHeight());
            GraphicsContext gc = backgroundLayer.getGraphicsContext2D();
            gc.setFill(Color.WHITE);
            gc.fillRect(0, 0, backgroundLayer.getWidth(), backgroundLayer.getHeight());
            canvasPane.getChildren().add(backgroundLayer);
        }
    
        @FXML
        private void handleAddLayer(ActionEvent event) { }
    }
    

    但什么也没发生——我本想得到一个白色画布的窗格,但我得到的却是同样的空窗格。

    有什么问题吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   SedJ601    7 年前

    canvasPane.getWidth() canvasPane.getHeight() 值很可能为零。 尝试:

    Canvas backgroundLayer = new Canvas(200, 200); 
    

    或:

    Canvas backgroundLayer = new Canvas(canvasPane.getPrefWidth(), canvasPane.getPrefHeight());