0

How can I add a custom class to an fxml file.

I've tried this adding this:

package gameName.FinishedClasses;
import javafx.scene.control.Button;

public class CardButton extends Button
{
  int cardID;

  public CardButton(String n , int m)
  {
    setText(n);
    cardID = m;
  }
  public CardButton(int m)
  {
    cardID = m;
  }
  public int getCardID()
  {
    return cardID;
  }
  public void setCardID(int n)
  {
    cardID =n;
  }
  public void setButtonText(String n)
  {
    setText(n);
  }
}

Like this:

 <CardButton mnemonicParsing="false" text="Button" fx:id="Button1R1C" cardID="0">
                 <padding>
                    <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
                 </padding>
                 <HBox.margin>
                    <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
                 </HBox.margin>
 </CardButton>

Stacktrace:

Caused by: java.lang.ClassNotFoundException: gameName.FinishedClasses$CardButton
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at javafx.fxml.FXMLLoader.loadTypeForPackage(FXMLLoader.java:2916)
at javafx.fxml.FXMLLoader.loadType(FXMLLoader.java:2905)
at javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2846)

It says it's not able to instantiate and I can't seem to figure out what the issue is.

Oladam
  • 39
  • 1
  • 6

1 Answers1

1

The FXMLLoader expects your class and package names to follow standard naming conventions. Specifically, since FinishedClasses is capitalized, the FXML import

<?import gameName.FinishedClasses.CardButton ?>

is interpreted as CardButton being an inner class in a class called FinishedClasses. Rename your packages correctly (i.e. all lower case) and it should work correctly.

James_D
  • 201,275
  • 16
  • 291
  • 322
  • This should still cause an error, since there is no constructor without parameters and none of the constructor parameters of the other constructors are annotated with `@NamedArg`, but at least it should solve the issue posted in the question... – fabian Mar 05 '17 at 08:20