java实现多功能交换拖拽拼图

不同于传统的计步拼图,本项目没有空白格的存在,依靠鼠标的点击事件进行图片的位置交换,可以根据需求选择本地的图片,代码中默认为F盘路径下的图片文件,可以根据需要进行更改或者去掉默认图片,该游戏实现图片重排,不同矩阵大小的拼图,其中添加了3*3,4*4,5*5,可以根据需求进行修改。同时可以是实现计时挑战模式,时间根据矩阵的大小而定,可以自己设置,美中不足的是,存在拼图成功之后线程没有中断的问题,读者可以自行感受修改。本游戏含有四个类,按钮Cell类,主控界面类Main,操作类Operate,显示原图类TotalPicture。

java多图拼接 java拼图拖动图片_拖拽

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;
              int width = 0;
              int height = 0;
              try
              {  

                  ImageIcon image = new ImageIcon(filepath);
                  image.setImage(image.getImage().getScaledInstance(400, 400, Image.SCALE_DEFAULT));
                  buf = new BufferedImage(400, 400,  
                        BufferedImage.TYPE_INT_RGB);
                   Graphics2D biContext = buf.createGraphics();
                   biContext.drawImage(image.getImage(), 0, 0, null);
                  width = 400/col;
                  height = 400/row;
              }catch(Exception e)
              {
                  System.out.println(e);
              }
              for(int i = 0; i < row; i++)
              {
                  for(int j = 0; j < col; j++)
                  {
                      num = i*col+j;//表示当前这个图像的坐标id,在数组中的下标
                      bufnew = buf.getSubimage(width*j, height*i, width, height);
                      icon = new ImageIcon(bufnew);//将图像转化成图标
                      cells[num] = new Cell(icon, num, width, height);//添加图标到每一个BUTTON按钮上面
                      cells[num].setLocation(width*j, height*i);
                  }
              }
              for(int i = 0; i <cells.length; i++)
              {
                      this.add(cells[i]);//将每一个按钮添加到当前这个面板上面
                      cells[i].addMouseListener(this);//空白格不添加监听机制
              }
          } 

          public void initt() {
              int num = 0;
              BufferedImage buf=null;
              BufferedImage bufnew = null;
              ImageIcon icon = null;
              int width = 0;
              int height = 0;
              try
              {  

                  ImageIcon image = new ImageIcon("F://temp/_11.jpg");
                  image.setImage(image.getImage().getScaledInstance(400, 400, Image.SCALE_DEFAULT));
                  buf = new BufferedImage(400, 400,  
                        BufferedImage.TYPE_INT_RGB);
                   Graphics2D biContext = buf.createGraphics();
                   biContext.drawImage(image.getImage(), 0, 0, null);
                  width = 400/col;
                  height = 400/row;
              }catch(Exception e)
              {
                  System.out.println(e);
              }
              for(int i = 0; i < row; i++)
              {
                  for(int j = 0; j < col; j++)
                  {
                      num = i*col+j;//表示当前这个图像的坐标id,在数组中的下标
                      bufnew = buf.getSubimage(width*j, height*i, width, height);
                      icon = new ImageIcon(bufnew);//将图像转化成图标
                      cells[num] = new Cell(icon, num, width, height);//添加图标到每一个BUTTON按钮上面
                      cells[num].setLocation(width*j, height*i);
                  }
              }
              for(int i = 0; i <cells.length; i++)
              {
                      this.add(cells[i]);//将每一个按钮添加到当前这个面板上面
                      cells[i].addMouseListener(this);//空白格不添加监听机制
              }
          } 

          public void OutOfOrder()//乱序----打乱图片的排布顺序
          {
              Random random = new Random();
              for(int i = 0 ; i <cells.length ; i++)
              {
                  int index1 = random.nextInt(cells.length);//cells的长度是9,但是他的上限是9,取不到9,所取值范围是0-8
                  int index2 = random.nextInt(cells.length);
                  int x = cells[index1].getX();
                  int y = cells[index1].getY();//获取下标是index1的数组元素按钮的坐标
                  cells[index1].setLocation(cells[index2].getX(), cells[index2].getY());
                  cells[index2].setLocation(x, y);
              }
          }
          public boolean IsWin()//判断游戏玩家是否赢
          {
              for(int i = 0; i <cells.length; i++)
              {
                  int x = cells[i].getX();
                  int y = cells[i].getY();
                  if((x/(400/col)+ (y/(400/row)) *3)!= i)
                  {
                      return false;
                  }
              }
              return true;
          }
          int x1,y1,x2,y2;
          Cell click1,click2;
          public void mouseClicked(MouseEvent e) {
                          if(k==0) {
                             click1=(Cell) e.getSource();
                            x1=click1.getX();
                            y1=click1.getY();
                            k=1;
                          }else {
                            click2=(Cell) e.getSource();
                            x2=click2.getX();
                            y2=click2.getY();
                            click1.setLocation(x2,y2);
                            click2.setLocation(x1, y1);
                            k=0;
                            if(IsWin()) {

                                int choice = JOptionPane.showConfirmDialog(null, "恭喜您过关了是否还来一局?", "提示", JOptionPane.YES_NO_OPTION);
                                if(choice == 0)//表示再来一局
                                {
                                    this.OutOfOrder();
                                }
                                else//表示退出游戏
                                    System.exit(1);

                          }
                        }
          }
        @Override
        public void mouseEntered(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
        @Override
        public void mouseExited(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
        @Override
        public void mousePressed(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
        @Override
        public void mouseReleased(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
}
package 拼图Dome;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TotalPicture extends JFrame {

    private JPanel contentPane;
    /**
     * Create the frame.
     */
    String filepath;
    public TotalPicture(String filepath) {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 501, 506);
        this.setVisible(true);
        contentPane = new JPanel();
        contentPane.setLayout(null);
        setContentPane(contentPane);

        JLabel lblNewLabel = new JLabel("");
        lblNewLabel.setBounds(10, 40, 465, 420);
        contentPane.add(lblNewLabel);

        int width = 465,height = 420;
        ImageIcon image = new ImageIcon(filepath);
        image.setImage(image.getImage().getScaledInstance(width, height, Image.SCALE_DEFAULT));
        lblNewLabel.setIcon(image);

        JButton button = new JButton("\u5173\u95ED");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        button.setFont(new Font("宋体", Font.PLAIN, 14));
        button.setBounds(0, 10, 93, 23);
        contentPane.add(button);
    }
}
package 拼图Dome;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Image;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.concurrent.TimeUnit;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.JTable;
public class Main extends JFrame implements Runnable{
    public  JPanel contentPane=new JPanel();
    /**
     * Create the frame.
     */
    Thread t;
    public  String path;
    int time,count=3;
    public Main() {

        super("拼图游戏");
        contentPane.setLayout(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 593, 483);
        setContentPane(contentPane);


        Operate op=new Operate(3,3);
        op.setBounds(154, 20, 400, 400);
        contentPane.add(op);
        op.setVisible(true);
        op.initt();
        path="F://temp/_11.jpg";

        JButton button = new JButton("查看原图");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                new TotalPicture(path);
            }
        });
        button.setFont(new Font("宋体", Font.PLAIN, 16));
        button.setBounds(10, 10, 106, 42);
        contentPane.add(button);

        JButton button_2 = new JButton("试玩新图");
        button_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                op.removeAll();
                op.repaint();
                path=op.getpath();
                contentPane.repaint();
                op.init();
                }
            }
        );
        button_2.setFont(new Font("宋体", Font.PLAIN, 16));
        button_2.setBounds(10, 75, 106, 42);
        contentPane.add(button_2);



        JButton button_3 = new JButton("图片重排");
        button_3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                op.OutOfOrder();
            }
        });
        button_3.setFont(new Font("宋体", Font.PLAIN, 16));
        button_3.setBounds(10, 138, 106, 42);
        contentPane.add(button_3);

        JLabel lblNewLabel = new JLabel("\u5207\u5272\u6570\u91CF\uFF1A");
        lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 16));
        lblNewLabel.setBounds(23, 256, 100, 27);
        contentPane.add(lblNewLabel);

        String[] str=new String[3];
        str[0]="3";str[1]="4";str[2]="5";
        JComboBox comboBox = new JComboBox(str);
        comboBox.setBounds(23, 293, 90, 27);
        contentPane.add(comboBox);
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int t=Integer.parseInt((String) comboBox.getSelectedItem());
                op.removeAll();
                op.row=t;
                op.col=t;
                count=t;
                op.cells=new Cell[t*t];
                contentPane.repaint();
                if(path.equals("F://temp/_11.jpg")) op.initt();
                else  op.init();
            }});

        JButton button_1 = new JButton("挑战模式");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) { 
                startT();
            }
        });
        button_1.setFont(new Font("宋体", Font.PLAIN, 16));
        button_1.setBounds(10, 204, 106, 42);
        contentPane.add(button_1);


        JLabel lblNewLabel_1 = new JLabel("\u5012\u8BA1\u65F6\uFF1A");
        lblNewLabel_1.setFont(new Font("宋体", Font.PLAIN, 16));
        lblNewLabel_1.setBounds(23, 330, 67, 27);
        contentPane.add(lblNewLabel_1);


    }
    public void startT() {
        t=new Thread(this);
        t.start();
    }
    public void  running(int k) {
        JTextField jl2 = new JTextField("");
        jl2.setFont(new Font("宋体", Font.PLAIN, 16));
        jl2.setBounds(55, 367, 68, 27);
        contentPane.add(jl2);
        jl2.setText("");
        jl2.setText(String.valueOf(k));

    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        int i = 0;
        if(count==3) i=20;
        if(count==4) i=40;
        if(count==5) i=60;
        for( ;i>=0;i--) {
            try{ running(i);
            Thread.sleep(1000);}catch(Exception e) {
            System.out.println(e.toString()); }
        }   
        int choice = JOptionPane.showConfirmDialog(null, "挑战失败,是否继续游戏?", "提示", JOptionPane.YES_NO_OPTION);
        if(choice == 0)//表示再来一局
        {
        }
        else//表示退出游戏
            System.exit(1);
    }

    public static void main(String []args) {
        Main m=new Main();
        m.setVisible(true);
    }
}

java多图拼接 java拼图拖动图片_拖拽_02