这是一个示例应用程序,它允许您将一些文本拖放到其他区域。
我想要放入的一个应用程序允许从 swing 放入,但不允许从 JavaFX 放入。
如果 JavaFX 位于 JFXPanel 和 Swing JFrame 中,则效果会很好。 如果它只是阶段中的纯 JavaFX,则它具有“禁止进入”标志并且不接受放置。
其他应用程序允许或阻止两者。但是这个应用程序接受 JFrame 的 drop,但不接受 Stage,实际的 Label 组件等是相同的。
import javafx.application.Application;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javax.swing.*;
public class DragViewExample extends Application {
@Override
public void start(Stage primaryStage) {
TextField tf = new TextField("Copied Text");
tf.setOnDragDetected(e -> {
Dragboard db = tf.startDragAndDrop(TransferMode.COPY);
db.setDragView(new Text(tf.getText()).snapshot(null, null), e.getX(), e.getY());
ClipboardContent cc = new ClipboardContent();
cc.putString(tf.getText());
db.setContent(cc);
});
tf.setOnDragDropped(event -> {
System.out.println("dropped");
});
tf.setOnDragDone(event -> {
System.out.println("done");
});
//FULL JAVAFX
Scene scene = new Scene(new StackPane(new HBox(10, tf)), 350, 75);
primaryStage.setScene(scene);
primaryStage.show();
//JAVAFX INSIDE SWING
// JFrame frame = new JFrame();
// JFXPanel fxPanel = new JFXPanel();
// Scene swingscene = new Scene(new StackPane(new HBox(10, tf)), 350, 75);
// fxPanel.setScene(swingscene);
// frame.setContentPane(fxPanel);
// frame.pack();
// frame.setVisible(true);
}
public static void main(String[] args) {
launch(args);
}
}
最佳答案
它不起作用,因为您尚未在 onDragOver
上实现:
此处进行拖放的正确方法是(其中源是文本字段):
source.setOnDragDetected(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
/* drag was detected, start a drag-and-drop gesture*/
/* allow any transfer mode */
Dragboard db = source.startDragAndDrop(TransferMode.ANY);
/* Put a string on a dragboard */
ClipboardContent content = new ClipboardContent();
content.putString(source.getText());
db.setDragView(new Text(tf.getText()).snapshot(null, null), e.getX(), e.getY());
db.setContent(content);
event.consume();
}
});
target.setOnDragOver(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
/* data is dragged over the target */
if (event.getDragboard().hasString()) {
/* allow for both copying and moving, whatever user chooses */
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
event.consume();
}
});
For a full answer follow the official oracle tutorial
( http://docs.oracle.com/javafx/2/drag_drop/jfxpub-drag_drop.htm )
关于javafx 拖放无法拖放到另一个应用程序中,可以从 swing 包装器中拖放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39642818/