pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

如何將按鈕拖放到 GridPane 上?

How to drag and drop button onto GridPane?(如何將按鈕拖放到 GridPane 上?)
本文介紹了如何將按鈕拖放到 GridPane 上?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

我正在做一個學校項目,創建一個簡單的戰艦游戲,我想使用拖放功能將按鈕從屏幕底部的 HBox 拖到玩家用來放置船只的 GridPane.但我無法讓它正常工作.這是 我的董事會圖片.

I'm working on a school project creating a simple battleship game and i want to use the Drag And Drop function to drag buttons from HBox on the bottom of the screen to the GridPane that the player uses to place ships on. But i can't get it to work properly. Here's a picture of my board per now.

我嘗試使用 button.setOnMouseDragged(e -> {CODE HERE});但它不起作用.

I have tried to use the button.setOnMouseDragged(e -> {CODE HERE}); but it doesnt work.

public class GridOrganizer {

    private BorderPane borderPane;

    public GridOrganizer() {
        borderPane = new BorderPane();
        borderPane.setStyle("-fx-background-color: grey;");
        borderPane.setPrefHeight(600);
        borderPane.setPrefWidth(600);
        createGrid();
    }

    public void createGrid() {
        //Creates the grids where the game is played and buttons/ships to place on grid

        GridPane playerGrid = new GridPane();
        GridPane enemyGrid = new GridPane();
        Insets padding = new Insets(10);

        //Create playergrid
        for (int i = 0; i < 10; i++) {
            playerGrid.getColumnConstraints().add(new ColumnConstraints(50)); //50 wide
            playerGrid.getRowConstraints().add(new RowConstraints(50)); 
        }
        //Create enemygrid
        for (int i = 0; i < 10; i++) {
            enemyGrid.getColumnConstraints().add(new ColumnConstraints(50)); //50 wide
            enemyGrid.getRowConstraints().add(new RowConstraints(50));
        }
        //looping through row and columns and adds buttons
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                Button button = new Button();
                button.setPrefHeight(50);
                button.setPrefWidth(50);
                GridPane.setConstraints(button, j, i); //(button, column, row)
                playerGrid.getChildren().add(button); //add button on each index

                button.setOnAction(new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent arg0) {
                        //HIT or MISS
                        System.out.println("Row: " + GridPane.getRowIndex(button) + ", Column: " + GridPane.getColumnIndex(button)); 
                        button.setStyle("-fx-background-color: grey;");
                    }
                });
            }
        }
        //..same with enemy grid
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                Button button = new Button();
                button.setPrefHeight(50);
                button.setPrefWidth(50);
                GridPane.setConstraints(button, j, i); //(button, column, row)
                enemyGrid.getChildren().add(button); //add button on each index

                button.setOnAction(new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent arg0) {
                        System.out.println("Row: " + GridPane.getRowIndex(button) + ", Column: " + GridPane.getColumnIndex(button)); 
                        button.setStyle("-fx-background-color: grey;");
                    }
                });
            }
        }

        //Make buttons for the ships
        Button rowboat = new Button("Rowboat");
        Button sailboat = new Button("Sailboat");
        Button submarine = new Button("Submarine");
        Button destroyer = new Button("Destroyer");
        Button battleship = new Button("Battleship");

        //Size the ship buttons to match game description
        battleship.setPrefHeight(50);
        battleship.setPrefWidth(250); //size 5
        destroyer.setPrefHeight(50);
        destroyer.setPrefWidth(200); //size 4
        submarine.setPrefHeight(50);
        submarine.setPrefWidth(150); //size 3
        sailboat.setPrefHeight(50);
        sailboat.setPrefWidth(150); //size 3
        rowboat.setPrefHeight(50);
        rowboat.setPrefWidth(100); //size 2

        //Drags button
        rowboat.setOnMouseDragged(e -> {
            //CODE HERE
        });

        //Drops button on grid
        //CODE HERE 


        sailboat.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {
                //PLACE SHIP
            }
        });

        submarine.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {
                //PLACE SHIP
            }
        }); 

        destroyer.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {
                //PLACE SHIP
            }
        });

        battleship.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {
                //PLACE SHIP
            }
        });

        HBox ships = new HBox(); //Horizontal box
        ships.getChildren().addAll(rowboat, sailboat, submarine, destroyer, battleship); //Add buttons to horizontal box

        //Add grids and ship buttons to pane with padding 
        borderPane.setLeft(enemyGrid); 
        BorderPane.setMargin(enemyGrid, padding);
        borderPane.setRight(playerGrid);
        BorderPane.setMargin(playerGrid, padding);
        borderPane.setBottom(ships);
        BorderPane.setMargin(ships, padding);
    }

    public Pane getGrid() {
        return borderPane;
    }
}

<小時>

推薦答案

這里的計劃是在拖動事件完成時使用創建按鈕所需的數據啟動一個拖動事件.在您的代碼中,您似乎已經將 Buttons 添加到 Grid 中.這意味著您只需要傳輸一個 String 來更改 Button's 文本.在我的代碼中,我在創建 Grid 時使用了 StackPane.然后我稍后創建并添加 Buttons.你的方法可能會更好.我已經看過那么遠了.我添加了一個 MCVE(來自 here 的更改代碼):

The plan here is to start a drag event with the data needed to create your button when the drag event finished. In your code, it looks like you have added the Buttons into the Grid already. That means you need to only transfer a String to change the Button's text. In my code, I am using a StackPane when creating the Grid. I then create and add the Buttons later. You approach may be better. I have looked that far. I have added an MCVE (Altered code from here):

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * Demonstrates a drag-and-drop feature.
 */
public class HelloDragAndDrop extends Application
{

    @Override
    public void start(Stage stage)
    {
        //Source Buttons.
        final Button boat1 = new Button("boat1");
        final Button boat2 = new Button("boat2");
        final Button boat3 = new Button("boat3");
        final Button boat4 = new Button("boat4");

        //Adding OnDragDetected to source Buttons.
        setOnDragDetected(boat1);
        setOnDragDetected(boat2);
        setOnDragDetected(boat3);
        setOnDragDetected(boat4);

        //Adding onDragDone to source Buttons.
        setOnDragDone(boat1);
        setOnDragDone(boat2);
        setOnDragDone(boat3);
        setOnDragDone(boat4);

        //Creating GridPane
        GridPane gridPane = new GridPane();
        gridPane.setVgap(5);
        gridPane.setHgap(5);
        gridPane.setPadding(new Insets(5, 5, 5, 5));
        gridPane.setStyle("-fx-background-color: black;");
        //Adding StackPane to every Cell in the GridPane and Adding the Target Events to each StackPane.
        for (int i = 0; i < 6; i++) {
            StackPane stackPane = new StackPane();
            stackPane.setPrefSize(150, 50);
            stackPane.setStyle("-fx-background-color: yellow;");
            setOnDragOver(stackPane);
            setOnDragEntered(stackPane);
            setOnDragExited(stackPane);
            setOnDragDropped(stackPane);

            gridPane.add(stackPane, i / 3, i % 3);
        }

        HBox root = new HBox(new VBox(boat1, boat2, boat3, boat4), gridPane);
        stage.setTitle("Hello Drag And Drop");
        Scene scene = new Scene(root, 400, 200);
        stage.setScene(scene);
        stage.show();
    }

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

    //source events handlers
    public void setOnDragDetected(Button source)
    {
        source.setOnDragDetected((MouseEvent event) -> {
            /* drag was detected, start drag-and-drop gesture*/
            System.out.println("onDragDetected");

            /* allow any transfer mode */
            Dragboard db = source.startDragAndDrop(TransferMode.ANY);

            /* put a string on dragboard */
            ClipboardContent content = new ClipboardContent();
            content.putString(source.getText());
            db.setContent(content);

            event.consume();
        });
    }

    public void setOnDragDone(Button source)
    {
        source.setOnDragDone((DragEvent event) -> {
            /* the drag-and-drop gesture ended */
            System.out.println("onDragDone");
            /* if the data was successfully moved, clear it */
//            if (event.getTransferMode() == TransferMode.MOVE) {
//                source.setText("");
//            }

            event.consume();
        });
    }

    //target event handlers
    public void setOnDragOver(StackPane target)
    {
        target.setOnDragOver((DragEvent event) -> {
            /* data is dragged over the target */
            System.out.println("onDragOver");

            /* accept it only if it is  not dragged from the same node
            * and if it has a string data */
            if (event.getGestureSource() != target
                    && event.getDragboard().hasString()) {
                /* allow for both copying and moving, whatever user chooses */
                event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
            }

            event.consume();
        });
    }

    public void setOnDragEntered(StackPane target)
    {
        target.setOnDragEntered((DragEvent event) -> {
            /* the drag-and-drop gesture entered the target */
            System.out.println("onDragEntered");
            /* show to the user that it is an actual gesture target */
            if (event.getGestureSource() != target
                    && event.getDragboard().hasString()) {
                target.setStyle("-fx-background-color: green;");
            }

            event.consume();
        });
    }

    public void setOnDragExited(StackPane target)
    {
        target.setOnDragExited((DragEvent event) -> {
            /* mouse moved away, remove the graphical cues */
            target.setStyle("-fx-background-color: transparent;");

            event.consume();
        });
    }

    public void setOnDragDropped(StackPane target)
    {
        target.setOnDragDropped((DragEvent event) -> {
            /* data dropped */
            System.out.println("onDragDropped");
            /* if there is a string data on dragboard, read it and use it */
            Dragboard db = event.getDragboard();
            boolean success = false;
            if (db.hasString()) {
                //target.setText(db.getString());
                Button tempBoat = new Button(db.getString());
                tempBoat.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
                target.getChildren().clear();
                target.getChildren().add(tempBoat);
                success = true;
            }
            /* let the source know whether the string was successfully
            * transferred and used */
            event.setDropCompleted(success);

            event.consume();
        });
    }    
}

在此代碼中,代表 BoatsButtons 都附加了 onDragDetectedonDragDone 事件處理程序.它們被認為是 Drag 事件的 Source/start.對于 GridPane 中的每個單元格,都會添加一個 StackPane.這些 StackPanes 被認為是 Target/放置拖動事件的區域.每個 StackPane 都附加了 onDragOveronDragEnteredonDragDroppedonDragExited.拖動事件完成后,接收該事件的 StackPane/Target 將獲得一個新的 Button 作為與 <代碼>源碼 按鈕.

In this code, the Buttons that represent the Boats all have onDragDetected and onDragDone event handlers attached. They are considered Source/start of a Drag event. For every cell in the GridPane, a StackPane is added. These StackPanes are considered the Target/areas to drop drag events. Each StackPane has onDragOver, onDragEntered, onDragDropped, and onDragExited attached. Once a drag event is complete, the StackPane/Target that receives the event gets a new Button as a child with the same name as the Source Button.

這篇關于如何將按鈕拖放到 GridPane 上?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Parsing an ISO 8601 string local date-time as if in UTC(解析 ISO 8601 字符串本地日期時間,就像在 UTC 中一樣)
How to convert Gregorian string to Gregorian Calendar?(如何將公歷字符串轉換為公歷?)
Java: What/where are the maximum and minimum values of a GregorianCalendar?(Java:GregorianCalendar 的最大值和最小值是什么/在哪里?)
Calendar to Date conversion for dates before 15 Oct 1582. Gregorian to Julian calendar switch(1582 年 10 月 15 日之前日期的日歷到日期轉換.公歷到儒略歷切換)
java Calendar setFirstDayOfWeek not working(java日歷setFirstDayOfWeek不起作用)
Java: getting current Day of the Week value(Java:獲取當前星期幾的值)
主站蜘蛛池模板: 针焰试验仪,灼热丝试验仪,漏电起痕试验仪,水平垂直燃烧试验仪 - 苏州亚诺天下仪器有限公司 | 回转炉,外热式回转窑,回转窑炉-淄博圣元窑炉工程有限公司 | 好物生环保网、环保论坛 - 环保人的学习交流平台 | 应急灯_消防应急灯_应急照明灯_应急灯厂家-大成智慧官网 | 水厂污泥地磅|污泥处理地磅厂家|地磅无人值守称重系统升级改造|地磅自动称重系统维修-河南成辉电子科技有限公司 | 英国公司注册-新加坡公司注册-香港公司开户-离岸公司账户-杭州商标注册-杭州优创企业 | 小程序开发公司_APP开发多少钱_软件开发定制_微信小程序制作_客户销售管理软件-济南小溪畅流网络科技有限公司 | 诗词大全-古诗名句 - 古诗词赏析 | 化妆品加工厂-化妆品加工-化妆品代加工-面膜加工-广东欧泉生化科技有限公司 | 碳化硅,氮化硅,冰晶石,绢云母,氟化铝,白刚玉,棕刚玉,石墨,铝粉,铁粉,金属硅粉,金属铝粉,氧化铝粉,硅微粉,蓝晶石,红柱石,莫来石,粉煤灰,三聚磷酸钠,六偏磷酸钠,硫酸镁-皓泉新材料 | 联系我们老街华纳娱乐公司官网19989979996(客服) | 精密钢管,冷拔精密无缝钢管,精密钢管厂,精密钢管制造厂家,精密钢管生产厂家,山东精密钢管厂家 | 千斤顶,液压千斤顶-力良企业,专业的液压千斤顶制造商,shliliang.com | 双齿辊破碎机-大型狼牙破碎机视频-对辊破碎机价格/型号图片-金联机械设备生产厂家 | 办公室家具公司_办公家具品牌厂家_森拉堡办公家具【官网】 | 玻璃钢格栅盖板|玻璃钢盖板|玻璃钢格栅板|树篦子-长沙川皖玻璃钢制品有限公司 | 螺旋丝杆升降机-SWL蜗轮-滚珠丝杆升降机厂家-山东明泰传动机械有限公司 | 高扬程排污泵_隔膜泵_磁力泵_节能自吸离心水泵厂家-【上海博洋】 | 钣金加工厂家-钣金加工-佛山钣金厂-月汇好 | 润东方环保空调,冷风机,厂房车间降温设备-20年深圳环保空调生产厂家 | hc22_hc22价格_hc22哈氏合金—东锜特殊钢 | 镀锌角钢_槽钢_扁钢_圆钢_方矩管厂家_镀锌花纹板-海邦钢铁(天津)有限公司 | 智慧食堂_食堂管理系统_食堂订餐_食堂消费系统—客易捷 | 广州番禺搬家公司_天河黄埔搬家公司_企业工厂搬迁_日式搬家_广州搬家公司_厚道搬迁搬家公司 | SRRC认证_电磁兼容_EMC测试整改_FCC认证_SDOC认证-深圳市环测威检测技术有限公司 | 铆钉机|旋铆机|东莞旋铆机厂家|鸿佰专业生产气压/油压/自动铆钉机 | 【官网】博莱特空压机,永磁变频空压机,螺杆空压机-欧能优 | 耐火浇注料-喷涂料-浇注料生产厂家_郑州市元领耐火材料有限公司 耐力板-PC阳光板-PC板-PC耐力板 - 嘉兴赢创实业有限公司 | 气动隔膜泵厂家-温州永嘉定远泵阀有限公司 | 澳门精准正版免费大全,2025新澳门全年免费,新澳天天开奖免费资料大全最新,新澳2025今晚开奖资料,新澳马今天最快最新图库 | 新型游乐设备,360大摆锤游乐设备「诚信厂家」-山东方鑫游乐设备 新能源汽车电池软连接,铜铝复合膜柔性连接,电力母排-容发智能科技(无锡)有限公司 | 解放卡车|出口|济南重汽|报价大全|山东三维商贸有限公司 | 缠绕机|缠绕膜包装机|缠绕包装机-上海晏陵智能设备有限公司 | 航空障碍灯_高中低光强航空障碍灯_民航许可认证航空警示灯厂家-东莞市天翔航天科技有限公司 | 冷却塔减速机器_冷却塔皮带箱维修厂家_凉水塔风机电机更换-广东康明冷却塔厂家 | 深圳昂为官网-气体分析仪,沼气分析仪,动态配气仪,气体传感器厂家 | 不锈钢水箱生产厂家_消防水箱生产厂家-河南联固供水设备有限公司 | 抓斗式清污机|螺杆式|卷扬式启闭机|底轴驱动钢坝|污水处理闸门-方源水利机械 | 预制直埋蒸汽保温管-直埋管道-聚氨酯发泡保温管厂家 - 唐山市吉祥保温工贸有限公司 | 河南正规膏药生产厂家-膏药贴牌-膏药代加工-修康药业集团官网 | 无锡装修装潢公司,口碑好的装饰装修公司-无锡索美装饰设计工程有限公司 |