Canvas 在JavaFX的画布上使用OnMouseMoved在x轴上移动形状
我创建Canvas 在JavaFX的画布上使用OnMouseMoved在x轴上移动形状,canvas,javafx,Canvas,Javafx,我创建形状,我需要在画布上的水平位置移动,也就是说,在x轴上,而不使用时间线 Class Square绘制正方形并插入画布位置 public class Square{ //calculate the position of the rand column to //draw and insert in the position of the canvas public void drawSquare(GraphicsContext gc) { //Sq
形状
,我需要在画布
上的水平位置移动
,也就是说,在x轴上
,而不使用时间线
Class Square
绘制正方形并插入画布
位置
public class Square{
//calculate the position of the rand column to
//draw and insert in the position of the canvas
public void drawSquare(GraphicsContext gc) {
//Square Shadow
//gc.rect(posX, posY, w, h);
gc.rect(1, 53, 50, 50);
gc.fill();
gc.beginPath();
//Square
gc.beginPath();
gc.setFill(Color.WHITE);
gc.setStroke(Color.BLACK);
gc.setLineWidth(2);
//gc.rect(posX, posY, w, h);
gc.rect(1, 53, 48, 48);
gc.fill();
gc.stroke();
}
}
新的画布实例
,具有高度=450
和宽度=600
Canvas canvas = new Canvas();
canvas.setHeight(450);
canvas.setWidth(600);
和GraphicsContext
到draw square
GraphicsContext gc = canvas.getGraphicsContext2D();
Square square= new Square();
square.drawSquare(gc);
shape
是create
和draw square
GraphicsContext gc = canvas.getGraphicsContext2D();
Square square= new Square();
square.drawSquare(gc);
还有drawSquare
和canvas
而鼠标事件
在画布
上移动方块
在X轴
上,我做了一些事情
但它不起作用,也许可以有另一个解决方案
canvas.setOnMouseMoved((MouseEvent event) -> {
//select the square and move on x-axis
});
有什么建议吗?试试这个(基于MikaelF)
public类主扩展应用程序{
@凌驾
公共无效开始(阶段primaryStage){
试一试{
矩形rectbund=新矩形();
BorderPane根=新的BorderPane();
场景=新场景(根,400400);
scene.getStylesheets().add(getClass().getResource(“application.css”).toExternalForm());
画布c=新画布(400400);
根集中心(c);
c、 addEventFilter(MouseEvent.ANY,new EventHandler()){
布尔值shouldDraw=false;
双dX,dY;
@凌驾
公共无效句柄(MouseEvent arg0){
如果(arg0.getEventType()==MouseEvent.MOUSE_按下){
shouldDraw=rectbund.contains(arg0.getX(),arg0.getY());
如果(应该绘制){
dX=arg0.getX();
dY=arg0.getY();
}
}else if(arg0.getEventType()==MouseEvent.MOUSE\u拖动){
如果(应该绘制){
double x=(arg0.getX()+rectbund.getX()-dX),
y=(arg0.getY()+rectbund.getY()-dY);
c、 getGraphicsContext2D(),
rectbind.getY(),rectbind.getWidth(),//50
getHeight());
直行的。setY(y);
矩形约束。setX(x);
dX=arg0.getX();
dY=arg0.getY();
}
}
}
});
c、 getGraphicsContext2D().setFill(Color.AQUAMARINE);
rectbund.xProperty().addListener(新的ChangeListener(){//),因为它们一起使用
@凌驾
更改公众假期(ObservableValue是在您的画布上绘制的其他东西吗?
?您最好使用。如果您正在将侦听器附加到画布上,则必须通过跟踪鼠标是否位于矩形上或上次绘制的位置来检查鼠标是否位于矩形上。使用矩形
将省去您的麻烦。此外,您还可以不绘制Pa在
中,使用
图形上下文#strokeRect方法会简单得多。我想说点什么,但我管好自己的事。:)