【发布时间】:2019-09-05 07:20:42
【问题描述】:
我正在尝试创建各种拼图游戏,其中我已将图像加载到 5x5 网格上,裁剪图像并将每个裁剪部分作为图标分配给以相同模式排列的 25 个按钮。我希望能够将鼠标指针从一个按钮拖动到另一个按钮并交换这两个按钮上的图标。
我尝试过使用多个 MouseListener 方法和 MouseMotionListener 方法,但到目前为止没有任何效果。
import java.awt.*;
import java.awt.event.*;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.Component;
import javax.swing.*;
//import java.awt.image.*;
public class ImageMove {
JFrame jf;
JButton[][] grid;
JLabel test;
public static void main(String[] args) {
ImageMove ob = new ImageMove();
ob.start();
}
public void start() {
jf = new JFrame();
JPanel gridPanel = new JPanel();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon img = new ImageIcon("download.jpg");
Image temp1= img.getImage();
img=new ImageIcon(temp1.getScaledInstance(500, 500, Image.SCALE_SMOOTH));
Image img1 = img.getImage();
gridPanel.setLayout(new GridLayout (5,5));
grid = new JButton[5][5];
for(int y=0;y<5;y++) {
for(int x=0; x<5; x++) {
Image image = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(img1.getSource(), new CropImageFilter(x * 500 / 5, y * 500 / 5, 100, 100)));
ImageIcon icon = new ImageIcon(image);
JButton temp = new JButton(icon);
temp.setTransferHandler(new TransferHandler("icon"));
temp.addMouseMotionListener(new DragMouseAdapter());
grid[x][y]=temp;
gridPanel.add(grid[x][y]);
}
}
test= new JLabel();
jf.getContentPane().add(BorderLayout.NORTH, test);
jf.add(gridPanel);
jf.pack();
jf.setSize(500, 500);
jf.setVisible(true);
}
class DragMouseAdapter extends MouseAdapter{
private int x, y;
public void mouseDragged(MouseEvent e) {
final int x0=MouseInfo.getPointerInfo().getLocation().x;
final int y0=MouseInfo.getPointerInfo().getLocation().y;
x=x0;
y=y0;
JButton c = (JButton) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
public void mouseReleased(MouseEvent e) {
JButton c = (JButton) e.getSource();
Icon icon = c.getIcon();
grid[((int)(x/100))][((int)(y/100))].setIcon(icon);
}
}
}
目前,程序将图标从第一个按钮复制到第二个按钮,即它用第一个按钮替换第二个按钮的图标,但第一个按钮保持不变。我希望完全交换这两个图标。接近尾声的 MouseDragged 方法正在执行所描述的行为,但 MouseReleased 似乎根本没有做任何事情。
非常感谢任何帮助。
【问题讨论】:
标签: java swing user-interface awt mouseevent