java实现多功能交换拖拽拼图
不同于传统的计步拼图,本项目没有空白格的存在,依靠鼠标的点击事件进行图片的位置交换,可以根据需求选择本地的图片,代码中默认为F盘路径下的图片文件,可以根据需要进行更改或者去掉默认图片,该游戏实现图片重排,不同矩阵大小的拼图,其中添加了3*3,4*4,5*5,可以根据需求进行修改。同时可以是实现计时挑战模式,时间根据矩阵的大小而定,可以自己设置,美中不足的是,存在拼图成功之后线程没有中断的问题,读者可以自行感受修改。本游戏含有四个类,按钮Cell类,主控界面类Main,操作类Operate,显示原图类TotalPicture。
package 拼图Dome;
import java.awt.Rectangle;
import javax.swing.Icon;
import javax.swing.JButton;
@SuppressWarnings("serial")
public class Cell extends JButton{
private static int IMAGEWIDTH;//设置按钮的宽度大小
private static int IMAGEHEIGHT;
private int ID;
public Cell(Icon icon, int id, int imagewidth, int height)//构造函数初始化,传入两个参数,一个是图像的图标,一个是该按钮的数组ID
{
this.setIcon(icon);
this.ID = id;
this.IMAGEWIDTH = imagewidth;
this.IMAGEHEIGHT = height;
this.setSize(IMAGEWIDTH, IMAGEHEIGHT);
}
public int getID() {
return ID;
}
public int getX()
{
return this.getBounds().x;
}
public int getY()
{
return this.getBounds().y;
}
}
package 拼图Dome;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import 拼图Dome.Cell;
public class Operate extends JPanel implements MouseListener{
public int row;
public int k=0;
public int col;//设置这个拼图的行列
Cell[] cells;
public String filepath;
int ImageWidth;
int ImageHeight;
public Operate()
{
}
public Operate(int row,int col) {
this.row=row;
this.col=col;
this.setLayout(null);
this.setBounds(154, 20, 400, 400);
this.setVisible(true);
cells= new Cell[row*col];//创建一个按钮对象数组
}
public String getpath() {
JFileChooser jf = new JFileChooser();
jf.showOpenDialog(this);//显示打开的文件对话框
File f = jf.getSelectedFile();//使用文件类获取选择器选择的文件
filepath = f.getAbsolutePath();//返回路径名
return filepath;
}
public void init() {
int num = 0;
BufferedImage buf=null;
BufferedImage bufnew = null;
ImageIcon icon = null;