这是一个示例应用程序,它允许您将一些文本拖放到其他区域。
我想放入的一个应用程序允许从摇摆而不是从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);
}
}
答案 0 :(得分:1)
由于您未在onDragOver
上实施,因此无法正常工作:
在这里进行拖放的正确方法是(其中source是textField ):
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();
}
});
如需完整答案,请参阅官方oracle教程
(http://docs.oracle.com/javafx/2/drag_drop/jfxpub-drag_drop.htm)