我有一个由 Tiles 组成的 4x4 gridpane 对象,扩展了 ImageView,我想创建通过鼠标拖放来更改连接 Tiles 位置的方法。我已经弄清楚如何获取开始拖动的第一个元素,但我无法获取拖放中的 ImageView 的引用。
瓷砖类
public class Tile extends ImageView {
protected int xCoordinate;
protected int yCoordinate;
protected boolean isMoveable;
protected ArrayList<Point2D> points = new ArrayList<>();
public Tile(int xCoordinate, int yCoordinate) {
this.xCoordinate = xCoordinate;
this.yCoordinate = yCoordinate;
super.setFitHeight(125);
super.setFitWidth(125);
}}
GridPane 代码
GridPane gridPane = new GridPane();
for (Tile tile : tiles){
gridPane.add(tile,tile.getXCoordinate(),tile.getYCoordinate());
}
StackPane centerPane = new StackPane();
centerPane.setStyle("-fx-background-color: white;");
centerPane.getChildren().add(gridPane);
centerPane.setPadding(new Insets(0,50,0,50));
我已经尝试过,但我不知道如何获取连接的图块的参考
gridPane.setOnMouseDragged(e->{
System.out.println(e.getTarget());
gridPane.setOnMouseReleased(e1->{
System.out.println(e1.getTarget());
});
});
我已经创建了用于更改位置的代码,但是当鼠标释放时我应该获得连接的图块的引用。
Oracle 提供了关于在 JavaFX 中使用 拖放 的优秀教程。
您可能想使用Dragboard,这是一种特殊的Clipboard。
注意事项
您实际上可能不需要移动您创建的图块。它们是 ImageView。
您可以将与源关联的图像放置在拖板中,并在拖放目标视图时更改目标视图中的图像。
您可以在拖板上设置dragView,用于拖动操作的视觉反馈。
您可以为拖板使用自定义内容类型而不是图像,这在链接的 Oracle 教程中进行了解释。
private static final DataFormat customFormat = new DataFormat("helloworld.custom");
将自定义数据放到拖板上时,请指定数据类型。请注意,数据必须是可序列化的。
从拖板读取数据时,需要进行适当的转换。
潜在方法
有两种方法可以处理图块显示。
创建单独的平铺视图和平铺模型界面。
当图块更改时,不要更改视图,仅更改支持视图的模型实例。视图观察其模型的变化并自动更新自身。不会创建新节点,也不会移动现有节点。
这就是下面示例中的方法。视图是 ImageView,模型是 Image。
在这种情况下,您将有关模型的信息放置在视图中。
将节点放置在网格中时,您可以记录其网格位置,例如通过节点中的成员值或在节点上设置用户数据。
将节点拖动到新位置时,您可以查询源节点的位置,然后使用以下方法交换网格中的源节点和目标节点:
GridPane.setConstraints(node, columnIndex, rowIndex)
这本质上是您在问题中提出的方法。
我不提供第二种潜在方法的实现。
示例
这些图像是手动拖动图块以重新排序之前和之后的网格图像。
该示例并不完全是您想要的,它纯粹作为示例提供,如果您希望使用其中的某些概念,您将需要对其进行调整。
ImageViewFactory 只是为了创建测试图像,您可以忽略该部分。
拖动特定的东西在 DragUtil 类中。
代码使用 Java 18 和更新的 Java 语言功能,因此要编译它,您需要启用适当的语言级别。
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Label;
import javafx.scene.effect.*;
import javafx.scene.image.*;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class TileDragApp extends Application {
private static final String TEXT = "abcdefghijklmnop";
private static final int GRID_SIZE = 4;
private static final int TILE_SIZE = 60;
@Override
public void start(Stage stage) {
ImageViewFactory imageViewFactory = new ImageViewFactory();
ImageView[] imageViews = imageViewFactory.makeImageViews(
TEXT,
TILE_SIZE
);
DragUtil dragUtil = new DragUtil();
GridPane grid = new GridPane();
for (int i = 0; i < TEXT.length(); i++) {
dragUtil.makeDraggable(imageViews[i], imageViews);
grid.add(imageViews[i], i % GRID_SIZE, i / GRID_SIZE);
}
grid.setGridLinesVisible(true);
grid.setPadding(new Insets(20));
stage.setScene(new Scene(grid));
stage.setResizable(false);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
class ImageViewFactory {
private static final String CSS =
"""
data:text/css,
""" +
// language=CSS
"""
.root {
-fx-background-color: azure;
}
.label {
-fx-font-size: 40px;
-fx-text-fill: navy;
}
""";
public ImageView[] makeImageViews(String text, int tileSize) {
List<Character> chars =
text.chars()
.mapToObj(
c -> (char) c
).collect(
Collectors.toList()
);
Collections.shuffle(chars);
return chars.stream()
.map(
c -> makeImageView(c, tileSize)
).toArray(
ImageView[]::new
);
}
private ImageView makeImageView(char c, int tileSize) {
Label label = new Label(Character.toString(c));
StackPane layout = new StackPane(label);
layout.setPrefSize(tileSize, tileSize);
Scene scene = new Scene(layout);
scene.getStylesheets().add(CSS);
SnapshotParameters snapshotParameters = new SnapshotParameters();
snapshotParameters.setFill(Color.AZURE);
Image image = layout.snapshot(snapshotParameters,null);
return new ImageView(image);
}
}
class DragUtil {
public void makeDraggable(ImageView imageView, Node[] acceptedSources) {
Effect highlight = createHighlightEffect(imageView);
imageView.setOnDragDetected(e -> {
Dragboard db = imageView.startDragAndDrop(TransferMode.MOVE);
ClipboardContent content = new ClipboardContent();
content.putImage(imageView.getImage());
db.setContent(content);
db.setDragView(makeSmaller(imageView.getImage()));
e.consume();
});
imageView.setOnDragOver(e -> {
if (e.getGestureSource() != imageView
&& Arrays.stream(acceptedSources)
.anyMatch(source -> source == e.getGestureSource())
&& e.getDragboard().hasImage()
) {
e.acceptTransferModes(TransferMode.MOVE);
imageView.setEffect(highlight);
e.consume();
}
});
imageView.setOnDragExited(e -> {
imageView.setEffect(null);
e.consume();
});
imageView.setOnDragDropped(e -> {
Dragboard db = e.getDragboard();
boolean success = false;
if (db.hasImage() && e.getGestureSource() instanceof ImageView source) {
source.setImage(imageView.getImage());
imageView.setImage(db.getImage());
success = true;
}
e.setDropCompleted(success);
e.consume();
});
}
private Image makeSmaller(Image image) {
ImageView resizeView = new ImageView(image);
resizeView.setFitHeight(image.getHeight() * 3 / 4);
resizeView.setFitWidth(image.getWidth() * 3 / 4);
SnapshotParameters snapshotParameters = new SnapshotParameters();
return resizeView.snapshot(snapshotParameters, null);
}
private Effect createHighlightEffect(Node n) {
ColorAdjust monochrome = new ColorAdjust();
monochrome.setSaturation(-1.0);
return new Blend(
BlendMode.MULTIPLY,
monochrome,
new ColorInput(
0,
0,
n.getLayoutBounds().getWidth(),
n.getLayoutBounds().getHeight(),
Color.PALEGREEN
)
);
}
}