【发布时间】:2017-07-08 10:35:09
【问题描述】:
我想画一条可以自我更新的直线,有点像您在 Microsoft Paint 中所做的。目前我可以在没有视觉反馈的情况下绘制它,在第一次单击时设置起始 x 和 y,当用户再次单击鼠标按钮时,它会设置结束 x 和 y,并将其添加到根子级。
我找到了这个答案how to draw a straight line in javafx that updates itself when the user moves the mouse?,这基本上是我想做的,并且基本上通过使用画布解决了我的问题。该线程中的其他用户已经建议或暗示没有画布会更容易实现,但没有提供示例。
因为我不能评论这个问题:有人可以给我看一个这个没有画布的例子吗?根据用户cmets,它应该更容易,但我无法弄清楚。
我拼凑了这个,这很有效,但我觉得有更好的方法来做到这一点:
private void registerMouseEventHandlers() {
final Toggle toggle = new Toggle();
final CustomLineMouseEventHandler lineMouseEventHandler = new CustomLineMouseEventHandler();
this.scene.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
toggle.clickCount++;
if (toggle.clickedTwice()) {
lineMouseEventHandler.setEndXAndYAndAddToSceneGroup(event.getX(), event.getY());
}
else {
lineMouseEventHandler.setCustomLine(new CustomLine());
lineMouseEventHandler.setStartXAndY(event.getX(), event.getY());
}
}
});
}
public class CustomLineMouseEventHandler {
private CustomLine customLine;
private List<CustomLine> customLines = new ArrayList<CustomLine>();
public void setCustomLine(CustomLine customLine) {
this.customLine = customLine;
this.customLine.setVisible(true);
}
public void setStartXAndY(double x, double y) {
this.customLine.setStartX(x);
this.customLine.setStartY(y);
LineManipulator.getGroup().getChildren().add(this.customLine);
}
public void updateLine(double x, double y) {
if (this.customLine != null) {
this.customLine.setEndX(x);
this.customLine.setEndY(y);
}
}
public void setEndXAndYAndAddToSceneGroup(double x, double y) {
this.customLine.setEndX(x);
this.customLine.setEndY(y);
this.customLines.add(customLine);
LineManipulator.getGroup().getChildren().remove(LineManipulator.getGroup().getChildren().size() - 1);
LineManipulator.getGroup().getChildren().add(this.customLine);
this.customLine = null;
}
}
【问题讨论】:
-
这个答案有什么问题? stackoverflow.com/a/42267118/1054140
-
@SergeyGrinev 答案没有错。在该线程中发布的用户表示可以在没有画布的情况下完成,但没有提供示例。在我的要求背后,没有什么比我的好奇心和学习欲望更多或更少。当然这是重复的,我什至发布了重复的链接以解释这个线程的开头......
-
哦,抱歉,我混淆了有无。要使其带有画布,只需使用
new Line而不是drawLine和 Pane 作为 LayoutManager。逻辑是一样的。 -
您可能想让您的问题更加独立,并且仅使用链接作为支持信息。就目前而言,您需要阅读另一个问题才能知道您在问什么。
-
@MarkRotteveel 完成。