我想绘制一条更新自己的直线,有点像你在Microsoft Paint中所做的那样。目前我可以在没有视觉反馈的情况下绘制它,在第一次单击时设置起始x和y,当用户再次单击鼠标按钮时,它设置结束x和y,并将其添加到根子项。
我找到了这个答案how to draw a straight line in javafx that updates itself when the user moves the mouse?,这基本上就是我想做的事情,并且基本上通过使用canvas来解决我的问题。该线程中的其他用户已建议或暗示如果没有画布更容易实现,但没有提供示例。
由于我无法评论这个问题:有人会告诉我一个没有画布的示例吗?根据用户评论,它应该更容易,但我无法弄明白。
我一起攻击了这个,但是我觉得有更好的方法可以做到这一点:
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;
}
}
答案 0 :(得分:3)
您可以轻松实现点击 - 拖动 - 释放用户输入样式:按下鼠标时向窗格添加新行,并在拖动鼠标时更新其终点:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class Draw extends Application {
private Line currentLine ;
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
pane.setOnMousePressed(e -> {
currentLine = new Line(e.getX(), e.getY(), e.getX(), e.getY());
pane.getChildren().add(currentLine);
});
pane.setOnMouseDragged(e -> {
currentLine.setEndX(e.getX());
currentLine.setEndY(e.getY());
});
Scene scene = new Scene(pane, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
如果您更喜欢点击 - 移动 - 点击用户体验按下 - 拖放 - 释放,请用
替换这两个事件处理程序 pane.setOnMouseClicked(e -> {
if (currentLine == null) {
currentLine = new Line(e.getX(), e.getY(), e.getX(), e.getY());
pane.getChildren().add(currentLine);
} else {
currentLine = null ;
}
});
pane.setOnMouseMoved(e -> {
if (currentLine != null) {
currentLine.setEndX(e.getX());
currentLine.setEndY(e.getY());
}
});