如何从JavaFX中的MouseEvent检索SVGPath内容

时间:2019-03-26 14:27:47

标签: svg javafx

我正在研究一个项目,该项目允许用户单击美国的一个州,然后显示一个测验,询问该州和首都是什么。状态是SVGPath。我需要鼠标事件处理程序来确定单击了哪个SVGPath才能确定测验数据。如何提取从处理程序中单击的SVGPath的坐标?

        //Mouse event handler for attacking states 
      EventHandler<MouseEvent> clickState = new EventHandler<MouseEvent>() { 
         @Override 
         public void handle(MouseEvent e) { 
            /*
             * Register quiz data here
             * 
             * QuizScreenController.setState(state);
             * QuizScreenController.setCapital(capital)
             */

             //Load quiz screen
            loadQuiz("State Quiz");
         }

      }; 
      //allStates is an SVGPath array that stores the individual state paths
      for(SVGPath currState : allStates) {  
          //Color states
          currState.setFill(Color.GRAY);
          registerHandler(currState, Color.GRAY, Color.BLACK);  
          //Register mouse event
          currState.addEventFilter(MouseEvent.MOUSE_CLICKED, clickState);
      }

1 个答案:

答案 0 :(得分:0)

尽管我很确定这不是执行此操作的最有效方法,但是我可以通过在EventFilter中设置MouseEvent来提取必要的数据。这样,我就可以简单地将foreach循环的当前路径迭代传递到事件中。

for(SVGPath currState : allStates) {  
              //Color states
              currState.setFill(Color.GRAY);
              registerHandler(currState, Color.GRAY, Color.BLACK);

              //Register mouse click
              currState.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
                 @Override 
                 public void handle(MouseEvent e) {
                     //Set quiz data
                    if(currState.getContent().equals(washington)) {
                      QuizScreenController.setState("washington");
                      QuizScreenController.setCapital("seattle");
                      selectedState = currState;
                  } else if(currState.getContent().equals(california)) {
                      QuizScreenController.setState("california");
                      QuizScreenController.setCapital("sacramento");
                    selectedState = currState;
                  }