创建一个Mousebirdner到Javafx矩形 [英] Creating a Mouselistner to Javafx rectangle
问题描述
我想在我的javafx矩形上创建一个mouselistner。
I want to create a mouselistner on my javafx rectangle.
我想按下它时矩形必须改变颜色吗?
the idea is that the rectangle has to change color when i press it?
有没有人知道如何在Javafx中为形状添加一个列表器?
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
}
});
然而我收到错误消息说
方法setOnMouseClicked(new EventHandler(){})
未定义类型Rectangle
the method setOnMouseClicked(new EventHandler(){}) is undefined for the type Rectangle
升级更多信息:
我对rect的唯一选择是:
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;
推荐答案
您的代码看起来正确并且匹配我能找到的任何示例。为了证明这一点,我举了一个简单的例子:
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.
这可能是一个长镜头,但请确保从<$引用 Rectangle
类型c $ c> JavaFX 库而不是 AWT
矩形,即确保导入为:
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;
而不是
import java.awt.Rectangle;
更新
根据我原来的评论,看起来好像你引用了 Rectangle
类型的错误导入。我不认识导入 com.sun.javafx.geom.Rectangle
,这是来自旧版本的JavaFX吗?
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?
您还引用了错误的 MouseEvent
类型。
You are also referencing the incorrect MouseEvent
type.
更改:
import com.sun.glass.events.MouseEvent;
收件人:
import javafx.scene.input.MouseEvent;
这篇关于创建一个Mousebirdner到Javafx矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!