2014-01-07 114 views
0

我在板上有幾個對象,我想通過座標獲取這些對象的索引。 我試過製作MouseEvent處理程序,並使用getBoundInParent()MouseInfo.getPointerInfo().getLocation()結合使用,但未成功。這些方法給了我不同的座標,並且無法匹配它們。Javafx - 光標相交形狀

我應該用光標的座標製作一個矩形並使用getBoundInParent().intersects方法嗎?

任何建議?

回答

2

在各形狀,提供setOnMouseEnteredsetOnMouseExited處理程序來捕捉鼠標進入和退出事件並記錄該鼠標位於形狀的索引。

假設

我想你需要相交光標熱點(例如,鼠標指針箭頭的尖端),而不是光標形狀或光標的矩形邊界(如熱點的交叉點是標準的方式該遊標工作)。

示例應用程序輸出

mouseover

  • 當鼠標懸停在圓,該圓將被高亮顯示,並且圓的索引(1)將顯示
  • 當鼠標懸停在矩形,矩形將被高亮顯示,矩形的索引(2)將會顯示。
  • 當您不將鼠標懸停在任一形狀上時,任何形狀都不會突出顯示,也不會顯示索引。

示例代碼比我想,這就是我需要的

import javafx.application.Application; 
import javafx.event.EventHandler; 
import javafx.geometry.Insets; 
import javafx.geometry.Pos; 
import javafx.scene.Scene; 
import javafx.scene.control.Label; 
import javafx.scene.effect.DropShadow; 
import javafx.scene.input.MouseEvent; 
import javafx.scene.layout.HBox; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.*; 
import javafx.stage.Stage; 

public class ShapeIntersector extends Application { 
    private static final Shape[] shapes = { 
      new Circle(50, Color.AQUAMARINE), 
      new Rectangle(100, 100, Color.PALEGREEN) 
    }; 

    private static final DropShadow highlight = 
      new DropShadow(20, Color.GOLDENROD); 

    @Override 
    public void start(Stage stage) throws Exception { 
     HBox layout = new HBox(40); 
     layout.setPadding(new Insets(30)); 
     layout.setAlignment(Pos.CENTER); 

     Label highlightedShapeLabel = new Label(" "); 
     highlightedShapeLabel.setStyle(
       "-fx-font-family: monospace; -fx-font-size: 80px; -fx-text-fill: olive" 
     ); 

     for (Shape shape: shapes) { 
      layout.getChildren().add(shape); 

      shape.setOnMouseEntered(new EventHandler<MouseEvent>() { 
       @Override 
       public void handle(MouseEvent event) { 
        shape.setEffect(highlight); 
        int idx = layout.getChildren().indexOf(shape) + 1; 
        highlightedShapeLabel.setText(
          "" + idx 
        ); 
       } 
      }); 

      shape.setOnMouseExited(new EventHandler<MouseEvent>() { 
       @Override 
       public void handle(MouseEvent event) { 
        shape.setEffect(null); 
        highlightedShapeLabel.setText(" "); 
       } 
      }); 
     } 

     layout.getChildren().add(highlightedShapeLabel); 

     stage.setScene(new Scene(layout)); 
     stage.show(); 
    } 

    public static void main(String[] args) { launch(args); } 
} 
+0

簡單。謝謝 ! :d – Adorjan