本文介绍了如何在棋盘游戏中移动跳棋?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Java创建了一个跳棋游戏界面,并将棋子放置在游戏板上的每个位置,但是现在我无法将棋子从一个正方形移到另一个正方形。


如何在棋盘游戏中移动跳棋?
下面是我尝试过的源代码:

  / * 
*要更改此许可证标头,请选择许可证标头在项目属性中。
*要更改此模板文件,请选择工具 |工具。模板
*并在编辑器中打开模板。
* /
软件包chackergame;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

/ **
*
* @author wenda
* /
公共课程CheckerGame扩展了JFrame {


private final int ROWS = 8;
private final int COLL = 8;

私人最终JPanel [] []正方形=新的JPanel [8] [8];
私人JPanel backgroundPanel;
私人最终JLabel statusBar = new JLabel( Red turn to play);
private JLabel lbPieces = new JLabel();

私有布尔值inDrag = false;

public CheckerGame(){

//将棋盘添加到分层窗格中
backgroundPanel = new JPanel();
backgroundPanel.setLayout(new GridLayout(8,8,0,0));

add(backgroundPanel,BorderLayout.CENTER);
add(statusBar,BorderLayout.SOUTH);


createSquare();
addPieces();

setIconImage(PiecesIcon.iconGame.getImage());
setTitle( Java Checkers); //设置标题游戏
setSize(500,500);

// setResizable(false);
setLocationRelativeTo(null);
setLocationByPlatform(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);

}

public void createSquare(){
for(int row = 0; row< ROWS; row ++){
for(int col = 0; col< COLL; col ++){

JPanel单元格=新的JPanel();
if((row + col)%2 == 1){
cell.setBackground(new Color(99,164,54));
// cell.setBackground(Color.BLACK);
}

if((row + col)%2 == 0){
cell.setBackground(new Color(247,235,164));
// cell.setBackground(Color.WHITE);
}
square [row] [col] =单元格;
backgroundPanel.add(square [row] [col]);
}
}
}

/ **
*在面板上添加块
* /
private void addPieces( ){

for(int row = 0; row< ROWS; row ++){
for(int col = 0; col< COLL; col ++){

lbPieces =新的JLabel();
lbPieces.setHorizo​​ntalAlignment(SwingConstants.CENTER);
//lb.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY,1));

if((row + col)%2 == 1){
if(row< 3){
lbPieces.setIcon(PiecesIcon.redPiece);
} else if(第4行){
lbPieces.setIcon(PiecesIcon.whitePiece);
}
}

square [row] [col] .setLayout(new BorderLayout());
square [row] [col] .add(lbPieces,BorderLayout.CENTER);
} // for col循环的结束
} // for行循环的结束
} // addPieces方法的结束

公共类MouseInput扩展MouseAdapter {


@Override
public void mousePressed(MouseEvent evt){
}

@ Override
public void mouseReleased(MouseEvent evt ){

}

@Override
public void mouseClicked(MouseEvent evt){

}

@Override
public void mouseDragged(MouseEvent evt){

}
}

/ **
* @param args命令行参数
* /
public static void main(String [] args){
new CheckerGame();
}

}


解决方案

基本问题是要从任何源容器( JPanel JLable ) >)到其他任何一个。

每个此类容器都可以是拖动组件的来源或放置对象。因此它需要同时支持两者。此类 JPanel 在以下 DragDropPane 类中实现。

要编写此代码,我是从


I have created a checkers game interface using java and placed pieces in each position on the game board but at the moment I am having trouble moving the pieces from one square to another.

How to moving checkers pieces in board game?Below is source code that I've tried:

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package chackergame;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

/**
 *
 * @author wenda
 */
public class CheckerGame extends JFrame {


    private final int ROWS = 8;
    private final int COLL = 8;

    private final JPanel[][] square = new JPanel[8][8];
    private JPanel backgroundPanel;
    private final JLabel statusBar = new JLabel(" Red turn to play");
    private JLabel lbPieces = new JLabel();

    private boolean inDrag = false;

    public CheckerGame() {

        //Add a chess board to the Layered Pane
        backgroundPanel = new JPanel();
        backgroundPanel.setLayout(new GridLayout(8, 8, 0, 0));

        add(backgroundPanel, BorderLayout.CENTER);
        add(statusBar, BorderLayout.SOUTH);


        createSquare();
        addPieces();

        setIconImage(PiecesIcon.iconGame.getImage());
        setTitle("Java Checkers");// set title game
        setSize(500, 500);

        //setResizable(false);
        setLocationRelativeTo(null);
        setLocationByPlatform(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);

    }

    public void createSquare() {
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLL; col++) {

                JPanel cell = new JPanel();
                if ((row + col) % 2 == 1) {
                    cell.setBackground(new Color(99, 164, 54));
                    // cell.setBackground(Color.BLACK);
                }

                if ((row + col) % 2 == 0) {
                    cell.setBackground(new Color(247, 235, 164));
                    // cell.setBackground(Color.WHITE);
                }
                square[row][col] = cell;
                backgroundPanel.add(square[row][col]);
            }
        }
    }

    /**
     * Add pieces to the board
     */
    private void addPieces() {

        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLL; col++) {

                lbPieces = new JLabel();
                lbPieces.setHorizontalAlignment(SwingConstants.CENTER);
                //lb.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));

                if ((row + col) % 2 == 1) {
                    if (row < 3) {
                        lbPieces.setIcon(PiecesIcon.redPiece);
                    } else if (row > 4) {
                        lbPieces.setIcon(PiecesIcon.whitePiece);
                    }
                }

                square[row][col].setLayout(new BorderLayout());
                square[row][col].add(lbPieces, BorderLayout.CENTER);
            } // end of for col loop
        } // end of for row loop
    } // end of addPieces method

    public class MouseInput extends MouseAdapter {


        @Override
        public void mousePressed(MouseEvent evt) {
        }

        @Override
        public void mouseReleased(MouseEvent evt) {

        }

        @Override
        public void mouseClicked(MouseEvent evt) {

        }

        @Override
        public void mouseDragged(MouseEvent evt) {

        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new CheckerGame();
    }

}
解决方案

The basic question is about dragging a component (in this case a JLable) from any source container (a JPanel) to any other one.
Every such container can be a source of the dragged component or a drop-target for it. so it needs to support both. Such JPanel is implemented in the following DragDropPane class.
To write this code I borrowed from MadProgrammer's answer which shows a solution for one source and one target.
It is a one-file mre : the entire code can be copy-pasted to LabelDnD.java file, and run. It demonstrates dragging a JLabel from panel to panel. Please note the comments:

import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDropEvent;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class LabelDnD{

    private static final int ROWS = 5, COLS = 5, GAP = 4;

    private Component makeContent() {

        JPanel content = new JPanel(new GridLayout(ROWS,COLS, GAP,GAP));
        content.setBorder(BorderFactory.createLineBorder(content.getBackground(), GAP));

        for(int i = 0; i < ROWS*COLS ; i++){
            content.add(new DragDropPane(String.valueOf(i)));
        }
        return content;
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame("Label Drag & Drop");
            f.add(new LabelDnD().makeContent());
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setLocationRelativeTo(null);
            f.pack();
            f.setVisible(true);
        });
    }
}

class DragDropPane extends JPanel implements DragGestureListener, DragSourceListener {

    private static final int W = 50, H = 50;
    private JComponent dragable;

    public DragDropPane(String text) {

        setBackground(Color.white);
        setPreferredSize(new Dimension(W, H));
        setBorder(BorderFactory.createLineBorder(Color.blue, 1));
        var label = new JLabel(text, JLabel.CENTER);
        setContent(label);
        new MyDropTargetListener(this);
        DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(
                                        this, DnDConstants.ACTION_COPY, this);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(W, H);
    }

    public void setContent(JComponent component) {

        removeAll();
        dragable = component;
        add(component);
        repaint();
    }

    //-->DragGestureListener implementation

    @Override
    public void dragGestureRecognized(DragGestureEvent dge) {

        // Create our transferable wrapper
        Transferable transferable = new TransferableComponent(dragable);

        // Start the "drag" process...
        DragSource ds = dge.getDragSource();
        ds.startDrag(dge, Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR), transferable, this);
        remove(dragable);
        revalidate(); repaint();
    }

    //-->DragSourceListener implementation

    @Override
    public void dragEnter(DragSourceDragEvent dsde) {}

    @Override
    public void dragOver(DragSourceDragEvent dsde) {}

    @Override
    public void dropActionChanged(DragSourceDragEvent dsde) {}


    @Override
    public void dragExit(DragSourceEvent dse) {}

    @Override
    public void dragDropEnd(DragSourceDropEvent dsde) {
        // If the drop was not successful, we need to
        // return the component back to it's previous
        // parent
        if (!dsde.getDropSuccess()) {
            setContent(dragable);
        }
    }
}

class MyDropTargetListener extends DropTargetAdapter {

    private final DragDropPane target;

    public MyDropTargetListener(DragDropPane target) {
        this.target = target;
        new DropTarget(target, DnDConstants.ACTION_COPY, this, true, null);
    }

    @Override
    public void drop(DropTargetDropEvent event) {

        try {

            var tr = event.getTransferable();
            var component = (JComponent) tr.getTransferData(TransferableComponent.component);

            if (event.isDataFlavorSupported(TransferableComponent.component)) {

                event.acceptDrop(DnDConstants.ACTION_COPY);
                target.setContent(component);
                event.dropComplete(true);

            } else {
                event.rejectDrop();
            }

        } catch (Exception e) {
            e.printStackTrace();
            event.rejectDrop();
        }
    }
}

class TransferableComponent implements Transferable {

    protected static final DataFlavor component =
            new DataFlavor(JComponent.class, "A Component");

    protected static final DataFlavor[] supportedFlavors = {
            component
    };

    private final JComponent componentToTransfer;

    public TransferableComponent(JComponent componentToTransfer) {

        this.componentToTransfer = componentToTransfer;
    }

    @Override
    public DataFlavor[] getTransferDataFlavors() {

        return supportedFlavors;
    }

    @Override
    public boolean isDataFlavorSupported(DataFlavor flavor) {

        return flavor.equals(component);
    }

    @Override
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {

        if (flavor.equals(component)) return componentToTransfer;
        else  throw new UnsupportedFlavorException(flavor);
    }
}


这篇关于如何在棋盘游戏中移动跳棋?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 10:37