Creating a Mouselistner to Javafx rectangle


Question

I want to create a mouselistner on my javafx rectangle.

the idea is that the rectangle has to change color when i press it?

Does anyone know how to add a listner to shapes in Javafx?

so far ive tried this:

    final Rectangle rect = new Rectangle();

        rect.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                // TODO Auto-generated method stub

            }
        });

However i get an error saying that

the method setOnMouseClicked(new EventHandler(){}) is undefined for the type Rectangle

Abit more information:

The only options i have for rect are these:

rect.add()
rect.contains()
rect.grow();
rect.hashcode()
rect.intersection();

and a few others of no importance.

The import i am using are the following:

import com.sun.glass.events.MouseEvent;
import com.sun.javafx.geom.Rectangle;
import com.sun.javafx.geom.Shape;
1
1
11/13/2012 12:38:34 PM

Accepted Answer

Your code looks correct and matches any examples I can find. To demonstrate this I have thrown together a quick example:

public class JavaFXApplication extends Application {

    Rectangle rect = new Rectangle(100,100);

    @Override
    public void start(Stage primaryStage) {
        rect.setFill(Color.BLUE);

        rect.setOnMouseClicked(new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent t) {
                rect.setFill(Color.RED);
            }
        });


        StackPane root = new StackPane();
        root.getChildren().add(rect);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

When the rectangle is clicked, the colour changes from blue to red.

This might be a long shot but make sure you are referencing the Rectangle type from the JavaFX library and not the AWT Rectangle i.e. make sure your import is:

import javafx.scene.shape.Rectangle;

and not

import java.awt.Rectangle;

Update

As per my original comment it looks as though you are referencing the wrong import for the Rectangle type. I don't recognise the import com.sun.javafx.geom.Rectangle, is this from an older version of JavaFX?

You are also referencing the incorrect MouseEvent type.

Change:

import com.sun.glass.events.MouseEvent;

To:

import javafx.scene.input.MouseEvent;
13
4/22/2014 12:03:05 PM

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