我想知道如何在JavaFX中绘制和连接线条或折线。 我的代码指责错误,在事件中我不能使用场景,根也不会使用任何这些变量,我会给出折线的输出。任何人都可以帮助我或使用我使用的这些数据结构发布代码(所以它不会那么令人困惑)?
这是我的代码:
public void start(Stage stage) {
VBox box = new VBox();
final Scene scene = new Scene(box, 300, 250);
scene.setFill(null);
double x=0.0,y=0.0;
EventHandler filter = new EventHandler<InputEvent>() {
@Override
public void handle(InputEvent event) {
Line line = new Line();
line.setStartX(0.0f);
line.setStartY(0.0f);
line.setEndX(100.0f);
line.setEndY(100.0f);
box.getChildren().add(line);
}
};
// Register the same filter for two different nodes
scene.addEventFilter(MouseEvent.MOUSE_PRESSED, filter);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
我想要的实际上是在活动中,能够展示每个Poliline州。
答案 0 :(得分:1)
此应用程序存储鼠标指针在按下鼠标时的位置。然后它在鼠标释放时存储鼠标指针的位置。接下来,它获取此信息并创建一条线并将该线绘制到场景中。
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
/**
*
* @author blj0011
*/
public class JavaFXApplication134 extends Application
{
double startX;
double startY;
@Override
public void start(Stage primaryStage)
{
AnchorPane root = new AnchorPane();
Scene scene = new Scene(root, 500, 500);
scene.setOnMousePressed((event)->{
startX = event.getSceneX();
startY = event.getSceneY();
});
scene.setOnMouseReleased((event)->{
double endX = event.getSceneX();
double endY = event.getSceneY();
Line line = new Line();
line.setStartX(startX);
line.setStartY(startY);
line.setEndX(endX);
line.setEndY(endY);
root.getChildren().add(line);
});
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
答案 1 :(得分:0)
尝试使用Polyline
类
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.shape.Polyline;
import javafx.stage.Stage;
public class PolylineDemo extends Application{
private Polyline polyline;
@Override
public void start(Stage primaryStage){
AnchorPane root = new AnchorPane();
Scene scene = new Scene(root, 500, 500);
scene.setOnMousePressed(event -> {
polyline = new Polyline();
root.getChildren().add(polyline);
});
scene.setOnMouseDragged(event -> {
polyline.getPoints().addAll(event.getX(), event.getY());
});
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args){
launch(args);
}
}