有错误麻烦评论下,谢谢! 具体可以看看注释
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class A extends JFrame implements MouseListener, MouseMotionListener {
JButton button1 = new JButton("拖动我移动!");
int x0, y0;
int x3, y3;
public A() {
setBounds(300, 300, 300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setTitle("java");
add(button1);
button1.addMouseListener(this);
button1.addMouseMotionListener(this);
setVisible(true);
setResizable(false);
}
public void mouseEntered(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
x3 = e.getX();
y3 = e.getY();
}
public void mouseClicked(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {
x0 = e.getX();
y0 = e.getY();
int x1 = button1.getBounds().x;
int y1 = button1.getBounds().y;
button1.setLocation(x0 + x1 - x3, y0 + y1 - y3);
}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
A test = new A();
}
}
动画演示
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1ebf9dceb25925764715a1f9f4e01b3d.gif)