Using custom javafx label doesn't work


Ok so I've created my own customer label, for this example it's extremely basic. What I did was extend the Javafx Label in my custom class called MyLabel. I'm also using FXML to create the GUI. Now when I do this I can't seem to instantiate with my custom class as I get this error.

"Can not set net.blacksquirreldevs.tests.MyLabel field net.blacksquirreldevs.tests.SampleLabelController.sampleLabel to javafx.scene.control.Label"

Here is the code for everything

package net.blacksquirreldevs.tests;

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

public class Main extends Application {

public void start(Stage primaryStage) throws Exception {
    AnchorPane anchorPane = (AnchorPane)     FXMLLoader.load(getClass().getResource("SampleLabel.fxml"));

    primaryStage.setScene(new Scene(anchorPane));;

public static void main(String... args) {

package net.blacksquirreldevs.tests;

import javafx.scene.control.Label;

public class MyLabel extends Label {

public MyLabel(String text) {

package net.blacksquirreldevs.tests;

import javafx.fxml.FXML;

import java.util.ResourceBundle;

public class SampleLabelController {

private ResourceBundle resources;
private URL location;
private MyLabel sampleLabel = new MyLabel("Hello world!");

void initialize() {
    assert sampleLabel != null : "fx:id=\"sampleLabel\" was not injected: check your FXML file 'SampleLabel.fxml'.";



And finally the fxml file SampleLabel.fxml

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

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.text.*?>

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="" fx:controller="net.blacksquirreldevs.tests.SampleLabelController">
<Label fx:id="sampleLabel" layoutX="153.0" layoutY="171.0" text="Sample Text">
    <Font name="Arial Bold" size="50.0" />

So what I want to know is why I can' declare, in my SamplelabelController class, the sampleLabel as MyLabel?

Hopefully I've explained this well enough, if not let me know and I'll try to go a bit more in detail.

5/4/2013 9:23:17 PM

Accepted Answer

You are using <Label ... in your FXML instead of <MyLabel

Beside that your MyLabel has a none default constructor and in this case you NEED to provide a builder named MyLabelBuilder so that FXMLLoader can create an instance of MyLabel

5/4/2013 9:43:16 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow