Java程序开发中如何实现,移动的小图片,不移出窗体,到窗体边框的时候自动改变方向?
展开全部
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
public class test extends JFrame{
private int xx, yy;
private boolean isDraging = false;
public test(){
setUndecorated(true); // 没有标题栏
setSize(200, 200);
setVisible(true);
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
isDraging = true;
xx = e.getX();
yy = e.getY();
}
public void mouseReleased(MouseEvent e) {
isDraging = false;
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if (isDraging) {
int left = getLocation().x;
int top = getLocation().y;
setLocation(left + e.getX() - xx, top + e.getY() - yy);
}
}
});
}
public static void main(String[] args) {
test t =new test();
t.setDefaultCloseOperation(3);
}
}
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
public class test extends JFrame{
private int xx, yy;
private boolean isDraging = false;
public test(){
setUndecorated(true); // 没有标题栏
setSize(200, 200);
setVisible(true);
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
isDraging = true;
xx = e.getX();
yy = e.getY();
}
public void mouseReleased(MouseEvent e) {
isDraging = false;
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if (isDraging) {
int left = getLocation().x;
int top = getLocation().y;
setLocation(left + e.getX() - xx, top + e.getY() - yy);
}
}
});
}
public static void main(String[] args) {
test t =new test();
t.setDefaultCloseOperation(3);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询