2017-01-18 45 views
1

在拖放過程中,在鼠標圖標旁邊顯示節點的半透明「副本」的最佳方式是什麼?JavaFX拖放鼠標圖標旁邊的自定義節點

基本上我有一些帶有彩色背景和文本標籤的HBox,並且我想給出它們在被拖動時「粘」到鼠標光標的外觀。

如果用戶可以直觀地驗證他們正在拖動的內容,而不是僅僅將鼠標光標更改爲各種拖動圖標,那很好。場景生成器往往會在拖動某些組件(如RadioButton)時執行此操作。

+2

你在做「平臺支持的拖放」(即你在某個節點上調用'startDragAndDrop')嗎?如果是這樣,你可以調用'Dragboard.setDragView(...)'來設置拖動的圖像光標。 –

+0

只是內部的,應用程序窗口之外沒有任何東西。 – User

+0

這不是我問的。 –

回答

2

節點的「半透明」副本通過在節點上調用snapshot(null, null)來完成,該節點返回WritableImage。然後,您將此WritableImage設置爲DragBoard的拖動視圖。這裏是一個小例子:

import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.control.Label; 
import javafx.scene.input.ClipboardContent; 
import javafx.scene.input.DataFormat; 
import javafx.scene.input.Dragboard; 
import javafx.scene.input.TransferMode; 
import javafx.scene.layout.HBox; 
import javafx.scene.layout.VBox; 
import javafx.stage.Stage; 

public class DragAndDrop extends Application { 
    private static final DataFormat DRAGGABLE_HBOX_TYPE = new DataFormat("draggable-hbox"); 

    @Override 
    public void start(Stage stage) { 
     VBox content = new VBox(5); 

     for (int i = 0; i < 10; i++) { 
      Label label = new Label("Test drag"); 

      DraggableHBox box = new DraggableHBox(); 
      box.getChildren().add(label); 

      content.getChildren().add(box); 
     } 

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

    class DraggableHBox extends HBox { 
     public DraggableHBox() { 
      this.setOnDragDetected(e -> { 
       Dragboard db = this.startDragAndDrop(TransferMode.MOVE); 

       // This is where the magic happens, you take a snapshot of the HBox. 
       db.setDragView(this.snapshot(null, null)); 

       // The DragView wont be displayed unless we set the content of the dragboard as well. 
       // Here you probably want to do more meaningful stuff than adding an empty String to the content. 
       ClipboardContent content = new ClipboardContent(); 
       content.put(DRAGGABLE_HBOX_TYPE, ""); 
       db.setContent(content); 

       e.consume(); 
      }); 
     } 
    } 

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

呵呵,不知道你可以傳遞(空,空)到快照,因爲我沒有足夠的RTFM ......嗯,這個工作無論如何。 – User