【发布时间】:2019-10-21 12:00:10
【问题描述】:
从 TextArea 拖动选定的文本时遇到奇怪的问题。文本被正确选择,但是当我拖动到目标位置时,文本的选择发生了变化,它随机减少了2-3个字符的选择。
这是完整的课程:
public class DnDMainController extends Application {
ClipboardContent cb = new ClipboardContent();
ObservableList<String> list = FXCollections.observableArrayList();
@FXML
private TextArea sourceText;
@FXML
private ListView<String> listView;
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("/main/DnD.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Simple Drag and Drop ExampleGame");
stage.show();
}
public static void main(String[] args) {
launch(args);
}
@FXML
void _detectDrag(MouseEvent event) {
Dragboard db = sourceText.startDragAndDrop(TransferMode.COPY);
cb.putString(sourceText.getSelectedText());
db.setContent(cb);
event.consume();
}
@FXML
void _dragExited(DragEvent event) {
String st = event.getDragboard().getString();
if (!(list.contains(st.trim()))) {
list.add(st);
listView.getItems().addAll(list);
}}
}
[![gif for DnD Issue][1]][1]
我在 TextField 上尝试过同样的方法,它在 TextField 上运行良好。但不幸的是,由于文本字符串很大,我无法使用 TextField。我不知道我做错了什么......
FXML 代码:
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="549.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="main.DnDMainController">
<children>
<TextArea fx:id="sourceText" layoutY="273.0" onDragDetected="#_detectDrag" prefHeight="127.0" prefWidth="550.0" text="There was once a velveteen rabbit, and in the beginning he was really splendid. He was fat and bunchy, as a rabbit should be; his coat was spotted brown and white, he had real thread whiskers, and his ears were lined with pink sateen. On Christmas morning, when he sat wedged in the top of the Boy’s stocking, with a sprig of holly between his paws, the effect was charming." wrapText="true">
<font>
<Font size="19.0" />
</font></TextArea>
<ListView fx:id="listView" layoutY="40.0" onDragExited="#_dragExited" onMouseClicked="#_callContext" prefHeight="200.0" prefWidth="516.0" />
<Label alignment="CENTER" contentDisplay="CENTER" layoutX="-2.0" layoutY="2.0" prefHeight="38.0" prefWidth="550.0" text="List of Words" textAlignment="CENTER" />
<Label alignment="CENTER" contentDisplay="CENTER" layoutX="7.0" layoutY="240.0" prefHeight="32.0" prefWidth="542.0" text="Story" textAlignment="CENTER" />
</children>
</AnchorPane>```
【问题讨论】:
-
请提供minimal, complete and verifiable example,以便我们尝试找出问题所在。对我来说,提供的信息太板了,无法找到问题。
-
我已经用完整的代码编辑了我的问题
-
发布您的
FXML。 -
使用 FXML 代码编辑
-
首先,您的代码结构让我知道您对基本 JavaFX 的了解并不好。您在
Controller中扩展Application。其次,基本的Java实践要求您在创建方法名称时遵循某些规则。使用_引导变量名是不好的做法。最后,搜索JavaFXDrag and Drop将为您提供大量有关如何正确执行此操作的基本教程。
标签: javafx drag-and-drop textarea drag