【发布时间】:2014-04-04 01:54:04
【问题描述】:
我有一个按钮,我想拖动它并在一段时间后放下它。 我在网上搜索了我遇到的最有用的东西是this链接。 与提供的链接一样,我希望将按钮拖动到光标所在的任何位置,只有当鼠标按钮上升时,按钮才会下降。 这个问题怎么解决?先谢谢了
【问题讨论】:
标签: java drag-and-drop javafx draggable drag
我有一个按钮,我想拖动它并在一段时间后放下它。 我在网上搜索了我遇到的最有用的东西是this链接。 与提供的链接一样,我希望将按钮拖动到光标所在的任何位置,只有当鼠标按钮上升时,按钮才会下降。 这个问题怎么解决?先谢谢了
【问题讨论】:
标签: java drag-and-drop javafx draggable drag
我设法制作了一个边框窗格并在其上放置了一个按钮。当您释放鼠标时,按钮会被拖动和释放!
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
【讨论】:
嘿,上面的代码对我不起作用。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class ButtonDraggable extends Application{
@Override
public void start(Stage primaryStage){
// button and pane are created
Button btOK = new Button("OK");
Pane pane = new Pane();
// this code drags the button
btOK.setOnMouseDragged(e -> {
btOK.setLayoutX(e.getSceneX());
btOK.setLayoutY(e.getSceneY());
});
// button added to pane and pane added to scene
pane.getChildren().add(btOK);
Scene scene = new Scene(pane,200, 250);
primaryStage.setTitle("A Draggable button");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args){
Application.launch(args);
}
}
【讨论】: