- import javax.swing.*;
- import java.awt.event.MouseListener;
- import java.awt.event.MouseMotionListener;
- import java.awt.event.MouseEvent;
- public class Ch100 implements MouseListener,MouseMotionListener{
- private JFrame fm;
- private JLabel lb;
- private ImageIcon icon_s,icon;
- private int x=100,y=100,x1,y1,x2,y2;
- private boolean isDrag=false;
- Ch100()
- {
- icon_s=new ImageIcon(Ch100.class.getResource("pic/star.png"));
- icon=new ImageIcon(Ch100.class.getResource("pic/santa.png"));
- lb=new JLabel(icon);
- lb.setBounds(0,0,128,128);
- lb.addMouseListener(this);
- lb.addMouseMotionListener(this);
- fm=new JFrame("滑鼠指標拖曳圖形");
- fm.setIconImage(icon_s.getImage());
- fm.setBounds(100,100,420,320);
- fm.setVisible(true);
- fm.setResizable(false);
- fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fm.setLayout(null);
- fm.add(lb);
- }
- public void mousePressed(MouseEvent e){
- if(isDrag)
- return;
- if(e.getButton()==1)
- isDrag=true;
- x1=e.getX();
- y1=e.getY();
- }
- public void mouseReleased(MouseEvent e){
- if(!isDrag)
- return;
- isDrag=false;
- }
- public void mouseClicked(MouseEvent e){}
- public void mouseEntered(MouseEvent e){}
- public void mouseExited(MouseEvent e){}
- public void mouseMoved(MouseEvent e){}
- public void mouseDragged(MouseEvent e){
- if(!isDrag)
- return;
- x2=e.getX();
- y2=e.getY();
- x+=(x2-x1);
- y+=(y2-y1);
- lb.setLocation(x, y);
- }
- public static void main(String[] args){
- new Ch100();
- }
- }
複製代碼 |