2017-06-29 281 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); 
    } 

}