Search code examples
javafxmouseclick-event

I don't understand mouse click events in javaFX


i have a question about javaFX, our code to change the color when clicking is:

bind if (rectangle.pressed) Color.RED else Color.GREEN

Now we want the color, when clicking so that's red, to stay. Can you guys help me?


Solution

  • Example Code 1: hover and pressed Variables

    The following code adds a yellow stroke to the square if the mouse hovers over the square. The fill color changes to red if the mouse button is pressed while hovering over the square.

    import javafx.scene.*;
    import javafx.scene.shape.*;
    import javafx.scene.paint.*;
    
    var r : Rectangle;
    Scene {
       content: [
           r = Rectangle {
               x: 20 y: 20 width: 50  height: 50
               fill:   bind if (r.pressed) Color.RED    else Color.GREEN
               stroke: bind if (r.hover)   Color.YELLOW else null
               strokeWidth: 10
           }
       ]
    }
    

    or maybe what you need is:

    onMouseClicked:function(e: MouseEvent)
                {
                 if(circle.fill == Color.GREEN)
                    circle.fill = Color.RED
                 else
                    circle.fill = Color.GREEN
                }