2015-04-02 53 views
1

(對不起,我的英文很差)如何停止JavaFX中的MouseEvent?

我不知道如何在JavaFX中停止鼠標事件。

當我按下按鈕然後按下大矩形時,此代碼會將小圖像生成一個大矩形,但如果再按一下,大矩形將重新生成一個新圖像。

我不想生成一個新的圖像,我該怎麼做?

 button.setOnAction((ActionEvent t) -> { 
     rectangle.setOnMouseClicked((MouseEvent me) -> { 

      Rectangle asdf = new Rectangle(48, 48, Color.TRANSPARENT); 

      StackPane imageContainer = new StackPane(); 
      ImageView image = new ImageView("firefox-icono-8422-48.png"); 
      imageContainer.getChildren().addAll(asdf, image); 
      imageContainer.setTranslateX(me.getX()); 
      imageContainer.setTranslateY(me.getY()); 

      enableDragging(imageContainer); 

      rootGroup.getChildren().add(imageContainer); 
      myList2.add(imageContainer); 

     }); 
    }); 

由於

PS:t.consume()和me.consume();什麼都不要。

回答

1

我不知道我已經正確地解釋你的問題,但如果你想「關閉」矩形上的鼠標點擊處理程序,你可以叫

rectangle.setOnMouseClicked(null); 

完整的示例:

import javafx.application.Application; 
import javafx.geometry.Pos; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.layout.StackPane; 
import javafx.scene.layout.VBox; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Rectangle; 
import javafx.stage.Stage; 

public class ActivateRectangleWithButton extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     Rectangle border = new Rectangle(100, 100, Color.TRANSPARENT); 
     Rectangle rect = new Rectangle(80, 80, Color.CORNFLOWERBLUE); 

     StackPane stack = new StackPane(border, rect); 

     Button button = new Button("Activate"); 
     button.setOnAction(evt -> { 
      border.setFill(Color.BLUE); 
      rect.setOnMouseClicked(me -> { 
       System.out.println("Active rectangle was clicked!"); 

       // de-activate: 
       border.setFill(Color.TRANSPARENT); 
       rect.setOnMouseClicked(null); 
      }); 
     }); 

     VBox root = new VBox(20, stack, button); 
     root.setAlignment(Pos.CENTER); 
     Scene scene = new Scene(root, 300, 300); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

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

你真的救了我一天。非常感謝! – Aniru 2015-04-02 20:09:04