2017-11-16 3 views
0

선상에 선 모양이 있다고 가정하고 그 위에 원 모양을 넣고 싶습니다. 원을 끌면 선을 좌우로 끌 수있는 원을 끌 수 있습니까? .줄에서 원을 끌기를 제한하는 방법. JavaFX

+0

은 드래그 노드 어떻게 드래그 할 수있다거나 그 행동에 설정되어 있습니까? – Matt

+0

setOnAction을 사용할 예정입니다. –

+1

코드를 게시하여 변경 사항을 조정할 수 있는지 확인할 수 있습니다. – Matt

답변

0

이 구현은 행을 따르고 행 끝을 전달하지 않습니다.

다음 키는 y = mx + b입니다. m = slope of lineb = 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; 
    }  
} 
관련 문제