如何将JPanel拖放到另一个JPanel

时间:2015-06-17 12:15:15

标签: java swing drag-and-drop jpanel

所以我一直试图制作this游戏1010!为学校项目。它不会成为一个应用程序,它将成为一个摇摆计划。正如您在此短视频中看到的那样,您必须将形状拖放到网格中。我目前有一个5x5网格和一个由Tiles制成的10x10网格,这是Tile类:

public class Tile extends JPanel{
private specialObservable observable;
private boolean isEmpty;
private Color gridColor;
private int width  = 40;
private int height = 40;

public Tile(Color gridColor){

    this.gridColor = gridColor;

    observable = new specialObservable();

    isEmpty = false;
    Border border = new MatteBorder(1, 1, 1, 1, Color.white);
    this.setBorder(border);
    this.setBackground(gridColor);

}

@Override
public Dimension getPreferredSize() {
    return new Dimension(width - 1, height - 1);
}

这个图块由Grid类使用,它创建了一个二维Tiles数组。然后将其传递到GridPanel和ShapeBox以创建这些网格的gridbaglayout。

public class Grid implements Observer{
    private Tile[][] grid;
    Tile tile;
    public Grid(int row, int col){
        grid = new Tile[row][col];
    }

    public JPanel createGrid(Color gridColor){
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        for (int row = 0; row < grid.length; row++) {
            for (int col= 0; col < grid[row].length; col++) {
                gbc.gridx = row;
                gbc.gridy = col;

                Tile tile = new Tile(gridColor);
                grid[row][col] = tile;
                panel.add(tile, gbc);

            }
        }
        return panel;
    }



    public Tile[][] getGrid() {
        return grid;
    }

    public void setGrid(int row, int col, Color color) {
        grid[row][col].setBackground(color);
    }
}

这是GridPanel(主网格)

public class GridPanel extends JPanel{

    private static Grid grid;
    private static final int height = 450;
    private final Color gridColor = Color.LIGHT_GRAY;

    public GridPanel(int width, Color mainColor){
        this.setLayout(new FlowLayout());
        this.setPreferredSize(new Dimension(width, height));
        this.setBackground(mainColor);

        setGrid(new Grid(10,10));
        JPanel gridPanel = getGrid().createGrid(gridColor);
        add(gridPanel);

    }

    public static Grid getGrid()
    {
        return grid;
    }

    public static void setGrid(Grid grid)
    {
        GridPanel.grid = grid;
    }
}

并且ShapeBox还包含一个网格

@SuppressWarnings("serial")
public class ShapeBox extends JPanel{

    private Grid grid;
    private final int height = 125;
    private final int width = 125;

    public ShapeBox(){
        this.setPreferredSize(new Dimension(width,height));
        grid = new Grid(5,5);
        add(grid.createGrid(Color.DARK_GRAY));
    }

    public void setShape(){
        grid.setGrid(0, 0, Color.red);
    }

}

现在我的问题是:如何将ShapeBox网格中的形状拖动到主GridPanel网格中?我曾尝试在点击网格后创建一个新对象并设置它与鼠标光标坐标的界限但是我无法使其工作。我很想知道任何因为我已经用完它们的原因。对不起,如果这是格式错误的stackoverflow问题,我对整个概念都不熟悉。

如果你喜欢这个项目的所有代码,请访问Github

0 个答案:

没有答案