java怎么设置图片跟随鼠标
1、//给个实例import java.awt.Color;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.MouseMotionListener;import java.net.URL;import javax.swing.BorderFactory;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;
2、public class ImageMove {static int x,y;public static void main(String[] args) throws Exception{JFrame f = new JFrame();f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.getContentPane().setLayout(null);//这个要设置成 null
3、//图标Iconicon = new ImageIcon(newURL("https://gss0.bdstatic.com/70cFsjip0QIZ8tyhnq/img/logo-zhidao.gif"));
4、// Icon icon = new ImageIcon("c:/logo-zhidao.gif");//本哪纳紧萄地图片文件JLabel l = new JLabel(icon);l.setSize(icon.getIconWidth(),icon.getIconHeight());l.setBorder(BorderFactory.createLineBorder(Color.red));f.getContentPane().add(l);f.setVisible(true);l.addMouseListener(new MouseAdapter(){public void mousePressed(MouseEvent e){x=e.getX();y=e.getY();}});
5、l.addMouseMotionListener(new MouseMotionListener(){public void mouseDragged(MouseEvent e) {JLabel l = (JLabel)e.getSource();l.setLocation(l.getX()+e.getX()-x,l.getY()+e.getY()-y);}public void mouseMoved(MouseEvent e) {}});}}