Logan Jahnke Logan Jahnke - 1 month ago 12
Java Question

How to create a node (Circle) while the mouse is hovering over a button in JavaFX?

I have an FXML file, along with a CSS file and a Controller.java file. While the mouse is hovering over a button from the FXML file,

e.g.

fx:id="load"


How do I create a Circle node onto the Stage?

I am currently doing this:

Note: The FXML and Controller are linked and all imports are accounted for.

// FXML:

<Button fx:id="load" layoutX="146.0" layoutY="307.0" mnemonicParsing="false"\
onMouseEntered="#hoverEnterLoad" onMouseExited="#hoverExitLoad"\
prefHeight="26.0" prefWidth="93.0" stylesheets="@title.css" />

// Controller:

public Controller {

@FXML private Button load;
private Circle choose = new Circle(210.0, 278.0, 15.0, Color.TRANSPARENT);

/**
* Shows circle
*/
@FXML void hoverEnterLoad(ActionEvent event) {
choose.setCenterX(210.0);
choose.setCenterY(278.0);
choose.setFill(Color.BLACK);
choose.setRadius(15.0);
} // hoverEnterLoad

/**
* Hides circle
*/
@FXML void hoverExitLoad(ActionEvent event) {
choose.setFill(Color.TRANSPARENT);
} // hoverExitLoad

} // Controller

Answer

I figured it out.

Add a transparent Circle into the FXML and edit it through the Controller.java instead of creating a new one.

// FXML:
// Added:

<Circle fx:id="selector" centerX="255.0" centerY="291.0" fill="TRANSPARENT" radius="5.0" stroke="TRANSPARENT" strokeType="INSIDE" />

// Controller:
// Added/Updated:

public Controller {

    @FXML private Button load;
    @FXML private Circle choose;

    /**                                                                                                                                                                              
     * Shows circle                                                                                                                                                                
     */
    @FXML void hoverEnterLoad(ActionEvent event) {
        choose.setCenterX(210.0);
        choose.setCenterY(278.0);
        choose.setFill(Color.BLACK);
        choose.setRadius(15.0);
    } // hoverEnterLoad                                                                                                                                                               

    /**                                                                                                                                                                              
     * Hides circle                                                                                                                                                                
     */
    @FXML void hoverExitLoad(ActionEvent event) {
        choose.setFill(Color.TRANSPARENT);
    } // hoverExitLoad

} // Controller