我可以交换面板,但还不够好。例如,如果面板 1 与面板 2 发生碰撞,它会交换,但如果面板 3 发生相同的碰撞,面板 3 也会移动到面板 1 的位置(我不想发生这种情况)。如果大约有 10 个面板,并且如果我想将 panel1 与 panel10 交换,那么当前逻辑是不可能的。谁能帮帮我。
以下是具有上述逻辑的代码:
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GDragAndDrop extends JFrame {
public GDragAndDrop() {
add(new op());
}
public static void main(String[] args) {
GDragAndDrop frame = new GDragAndDrop();
frame.setTitle("GDragAndDrop");
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);// Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class op extends JPanel implements MouseListener, MouseMotionListener {
JPanel p;
Point pPoint;
Point p1;
Point p2;
MouseEvent pressed;
JPanel[] panels = new JPanel[3];
public op() {
int b = 3;
int a = 0;
for (int i = 0; i < b; i++) {
panels[i] = new JPanel();
panels[i].setBackground(Color.cyan);
panels[i].setBorder(new LineBorder(Color.black));
a = a + 20;
panels[i].setPreferredSize(new Dimension(a, 400));
panels[i].addMouseListener(this);
panels[i].addMouseMotionListener(this);
panels[i].setBorder(new LineBorder(Color.black));
panels[i].setVisible(true);
panels[i].add("Center", new JLabel("To Move" + i));
this.add(panels[i]);
}
}
public JPanel getPanelColliding(JPanel dragPanel) {
Rectangle rDrag = dragPanel.getBounds();
for (int i = 0; i < 3; i++) {
if (panels[i] == dragPanel)
continue;
Rectangle r = panels[i].getBounds();
if (r.intersects(rDrag)) {
return panels[i];
}
}
return null;
}
public void mousePressed(MouseEvent e) {
int b = 3;
for (int i = 0; i < b; i++) {
if (e.getSource() == panels[i]) {
pressed = e;
p2 = panels[i].getLocation();
}
}
}
@Override
public void mouseDragged(MouseEvent arg0) {
int b = 3;
for (int i = 0; i < b; i++) {
if (arg0.getSource() == panels[i]) {
pPoint = panels[i].getLocation(pPoint);
int x = pPoint.x - pressed.getX() + arg0.getX();
int y = pPoint.y - pressed.getY() + arg0.getY();
if (getPanelColliding(panels[i]) != null) {
JPanel DragP = new JPanel();
DragP = getPanelColliding(panels[i]);
p1 = getPanelColliding(panels[i]).getLocation(p1);
int x1 = pPoint.x - pressed.getX() + arg0.getX();
int y1 = pPoint.y - pressed.getY() + arg0.getY();
panels[i].setLocation(x1, y1);
DragP.setLocation(p2);
} else
panels[i].setLocation(x, y);
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
}
}