gpt4 book ai didi

java - Javafx 中的拖动按钮

转载 作者:行者123 更新时间:2023-11-29 05:27:42 26 4
gpt4 key购买 nike

我有一个按钮,我想拖动它并在一段时间后放下它。我在网上搜索我遇到的最有用的东西是 this关联。与提供的链接一样,我希望将按钮拖动到光标所在的任何位置,只有当鼠标按钮上升时,按钮才应该下降。如何解决这个问题?提前致谢

最佳答案

我设法制作了一个 borderPane 并在其上放置了一个按钮。当您释放鼠标时,按钮会被拖动并释放!

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class ButtonDraggable extends Application {

@Override
public void start(Stage stage) throws Exception {
BorderPane borderPane = new BorderPane();
borderPane.setPrefSize(800, 600);
final Button button = new Button("Drag ME !");

final Delta dragDelta = new Delta();
button.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
// record a delta distance for the drag and drop operation.
dragDelta.x = button.getLayoutX() - mouseEvent.getSceneX();
dragDelta.y = button.getLayoutY() - mouseEvent.getSceneY();
button.setCursor(Cursor.MOVE);
}
});
button.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
button.setCursor(Cursor.HAND);
}
});
button.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
button.setLayoutX(mouseEvent.getSceneX() + dragDelta.x);
button.setLayoutY(mouseEvent.getSceneY() + dragDelta.y);
}
});
button.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
button.setCursor(Cursor.HAND);
}
});

borderPane.setCenter(button);

Scene scene = new Scene(borderPane);

stage.setScene(scene);
stage.show();

}

// records relative x and y co-ordinates.
class Delta {
double x, y;
}

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

}

如有任何疑问,请随时发表评论!

-AA

关于java - Javafx 中的拖动按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22139615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com