简体   繁体   中英

Add annotation to javafx custom control

I want to create a custom button using Javafx 8 that i can initialize using an annotation. But on the initialization of the button, only the FXML annotation appeared. How can I create the custom button with the annotation?

Annotation:

@Retention( RetentionPolicy.RUNTIME )
@Target(ElementType.FIELD)
public @interface Anno {

String someAction();

String someValue();
}

Class constructor:

    public CustomButton() {
    super();
    if (this.getClass().isAnnotationPresent(Anno.class)) {
        Anno anno = this.getClass().getAnnotation(Anno.class);
        setAction(anno.someAction());
        setValue(anno.someValue());
    }
    initialize();
}

Calling the custom button:

@FXML
@Anno(someAction = "someAction", someValue = "Hello")
private CustomButton button;

Is there a way to so?

I think it is not possible in the way you want this. The constructor of your CustomButton is looking for an annotation on the CustomButton class rather than the field it is assigned to, meaning it will never find the right annotation. And as far as I know there is no easy way to obtain the controller instance and the field reference from the constructor call to fix this issue.

So maybe you should try to follow this tutorial enabling the ability to set those fields in the .fxml file instead.

You don't need to create your own annotation. Using reflexion would be useless and complex.

To answer directly the question, the annotation is on field level, not on Type level, that's why you don't obtain your "Anno" annotation instance.

Whatever, the important thing is that you have to initialize the values of your button either in a FXML file, or in the controller.

You may want to see the tutorial from Oracle: https://blogs.oracle.com/jmxetc/entry/connecting_scenebuilder_edited_fxml_to

So in the FXML:

  <Button fx:id="myButton" text="a text" onAction="#myAction"/>

Or the equivalent in a controller

Just Declare the button in FXML

   <Button fx:id="myButton" />

Then bind the action in the controller

  public class MyController

  @FXML Button myButton;

@FXML
public void initialize(){
   myButton.setText("a text")
   myButton.setOnAction(this::myAction);
}

Edit: Your question was about "Custom" component, if your difficulty is here, note that you can add javaFX properties, generate getters/setters using e(fx)clipse plugin, or equivalent, then thie accessors will be accessible the same way in both FXML /controllers. If you want more detail about this, let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM