2017-06-29 280 views
-1

我想知道如何绘制和连接JavaFX中的线条或多段线。 我的代码指出错误,在事件中我不能使用场景,也不会使用root或任何这些变量来输出折线。任何人都可以使用我使用的这些数据结构来帮助我或发布代码(所以它不会那么混乱)?如何在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

你得到什么错误? –

+0

我在建模时遇到了问题,我想通过连接它们的线路来解决问题。在这一行中: Box.getChildren()。添加(line); 每次事件运行时我都无法添加到框中?我不理解如何与鼠标事件沟通我的盒子 –

+2

在问题中,你说它给出了一个错误。什么是实际的错误?当我运行你发布的代码时,我没有看到任何错误(我看到了行,但可能没有做你想做的事)。 –

回答

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); 
    } 

}