2017-11-16 11 views
0

私はペイン上に線の形があり、円の形をしたいとします。どのようにして円をドラッグすることができますか? 。行の円のドラッグを制限する方法。 JavaFX

+0

それはドラッグ可能なノードどのようにそれをドラッグすることがされているか、それがアクションに設定されていますか? – Matt

+0

私はsetOnActionを計画しています –

+1

あなたのコードの一部を投稿して、あなたがそれを微調整するために何をしているか見ることができますか – Matt

答えて

0

この実装は行の後にあり、行末を渡しません。

以下のキーはy = mx + bです。 m = slope of lineおよびb = y-intercept。ここで

は、粗実装です:

import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.layout.AnchorPane; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Circle; 
import javafx.scene.shape.Line; 
import javafx.stage.Stage; 

/** 
* 
* @author blj0011 
*/ 
public class JavaFXApplication42 extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     AnchorPane root = new AnchorPane(); 

     Line line = new Line(20, 120, 70, 170); 
     line.setStrokeWidth(3); 

     //When the line is clicked by the mouse add a circle 
     line.setOnMouseClicked((mouseClickedEvent)->{ 
      Circle c1 = new Circle(mouseClickedEvent.getSceneX(), mouseClickedEvent.getSceneY(), 25, Color.BLUE); 
      //When the circle is dragged follow the line 
      c1.setOnMouseDragged(mouseDraggedEvent -> { 
       double slope = lineSlope(line.getStartX(), line.getEndX(), line.getStartY(), line.getEndY()); 
       double yIntercept = yIntercept(slope, line.getStartX(), line.getStartY()); 
       c1.setCenterY(setCenterY(slope, mouseDraggedEvent.getSceneX(), yIntercept)); 
       c1.setCenterX(mouseDraggedEvent.getSceneX()); 

       //Bound checks to make sure circle does not go pass the line ends 
       if(c1.getCenterX() > line.getEndX()) 
       { 
        c1.setCenterX(line.getEndX()); 
       } 
       else if(c1.getCenterX() < line.getStartX()) 
       { 
        c1.setCenterX(line.getStartX()); 
       } 

       if(c1.getCenterY() > line.getEndY()) 
       { 
        c1.setCenterY(line.getEndY()); 
       } 
       else if(c1.getCenterY() < line.getStartY()) 
       { 
        c1.setCenterY(line.getStartY()); 
       } 
      }); 
      root.getChildren().add(c1); 
     }); 



     root.getChildren().add(line); 

     Scene scene = new Scene(root, 300, 250); 

     primaryStage.setTitle("Hello World!"); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     launch(args); 
    } 

    double lineSlope(double x1, double x2, double y1, double y2) 
    { 
     if(x2 - x1 == 0) 
     { 
      return 0; 
     } 

     return (y2 - y1)/(x2 - x1); 
    } 

    double yIntercept(double slope, double x1, double y1) 
    { 
     return y1 - (slope * x1); 
    } 

    double setCenterY(double slope, double x, double yIntercept) 
    { 
     return slope * x + yIntercept; 
    }  
} 
関連する問題