我的总体目标是创建一个拼图游戏,使用mousedrag在GUI屏幕上移动一组图像。我目前的问题是制作这种捕捉功能,当鼠标拖动图像释放时,图像将捕捉到预定的位置。这是我想要创建"盒子"的地方。我想为16个拼图创建16个盒子,并在释放鼠标时使用它们的坐标作为图像的捕捉位置。 (当你在悬停一般区域时,如何在拼图游戏中将这些部分捕捉到正确的位置)。我试图制作16个JPanels,但我不知道这是否是聪明的方法。而且,似乎我甚至无法将JPanel添加到我的JLayeredPane。我试图为其中一个JPanel设置边框,以帮助我查看它是否已添加,但事实并非如此。
鼠标拖动工作正常,一切正常。我只是希望能够添加某种盒子的表示形式,鼠标释放后的图像会捕捉到盒子的位置。如果您对此问题有任何见解,请与我们联系!
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Gui1 {
public static void main(String[] args) {
new Gui1();
}
public Gui1() { //Constructor for setting up the GUI
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JLayeredPane pane = new JLayeredPane();
JFrame frame = new JFrame("Testing");
JPanel canvas1 = new JPanel();
JPanel canvas2 = new JPanel();
JPanel canvas3 = new JPanel();
JPanel canvas4 = new JPanel();
JPanel canvas5 = new JPanel();
JPanel canvas6 = new JPanel();
JPanel canvas7 = new JPanel();
JPanel canvas8 = new JPanel();
JPanel canvas9 = new JPanel();
JPanel canvas10 = new JPanel();
JPanel canvas11 = new JPanel();
JPanel canvas12 = new JPanel();
JPanel canvas13 = new JPanel();
JPanel canvas14 = new JPanel();
JPanel canvas15 = new JPanel();
JPanel canvas16 = new JPanel();
canvas1.setPreferredSize(new Dimension(300,300));
canvas1.setBorder(BorderFactory.createLineBorder(Color.blue,10));
pane.add(canvas1, JLayeredPane.DEFAULT_LAYER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ImageGrab());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}