本帖最後由 tonyh 於 2016-6-16 13:10 編輯
實作 MouseListener 與 MouseMotionListener 介面, 以完成滑鼠指標拖曳圖形之動作.
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.ImageIcon;
- import java.awt.event.MouseListener;
- import java.awt.event.MouseMotionListener;
- import java.awt.event.MouseEvent;
- public class Ch90 implements MouseListener,MouseMotionListener{
-
- private JFrame fm;
- private JLabel lb;
- private ImageIcon icon,target;
- private int x=100,y=100,x1,y1,x2,y2;
- private boolean isDrag=false;
-
- Ch90()
- {
- icon=new ImageIcon(Ch90.class.getResource("pic/star.png"));
- target=new ImageIcon(Ch90.class.getResource("pic/santa.png"));
-
- lb=new JLabel(target);
- lb.setBounds(x, y, 128, 128);
- lb.addMouseMotionListener(this);
- lb.addMouseListener(this);
-
- fm=new JFrame("滑鼠指標拖曳圖形");
- fm.setBounds(100, 100, 420, 320);
- fm.setIconImage(icon.getImage());
- fm.setVisible(true);
- fm.setResizable(false);
- fm.setLayout(null);
- fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- 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 mouseDragged(MouseEvent e)
- {
- if(!isDrag)
- return;
- x2=e.getX();
- y2=e.getY();
- x+=(x2-x1);
- y+=(y2-y1);
- lb.setLocation(x, y);
- }
- public void mouseMoved(MouseEvent e){}
-
- public static void main(String[] args) {
- Ch90 app=new Ch90();
- }
- }
複製代碼 |