返回列表 發帖
  1. import javax.swing.*;
  2. import java.awt.event.*;

  3. public class Ch100 implements MouseListener, MouseMotionListener{
  4.         
  5.         private JFrame fm;
  6.         private JLabel lb;
  7.         private ImageIcon icon, target;
  8.         private int x=100, y=100, x1, y1, x2, y2;
  9.         
  10.         Ch100()
  11.         {
  12.                 icon=new ImageIcon(Ch100.class.getResource("pic/star.png"));
  13.                 target=new ImageIcon(Ch100.class.getResource("pic/santa.png"));
  14.                
  15.                 lb=new JLabel(target);
  16.                 lb.setBounds(x, y, 128, 128);
  17.                 lb.addMouseListener(this);
  18.                 lb.addMouseMotionListener(this);
  19.                
  20.                 fm=new JFrame("滑鼠指標拖曳圖形");
  21.                 fm.setBounds(100, 100, 420, 320);
  22.                 fm.setIconImage(icon.getImage());
  23.                 fm.setVisible(true);
  24.                 fm.setResizable(false);
  25.                 fm.setLayout(null);
  26.                 fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  27.                 fm.add(lb);
  28.         }
  29.         
  30.         public void mousePressed(MouseEvent e){
  31.                 x1=e.getX();
  32.                 y1=e.getY();
  33.                 //System.out.println(x1+" "+y1);
  34.         }
  35.         public void mouseReleased(MouseEvent e){}
  36.         public void mouseClicked(MouseEvent e){}
  37.         public void mouseEntered(MouseEvent e){}
  38.         public void mouseExited(MouseEvent e){}
  39.         public void mouseDragged(MouseEvent e){
  40.                 x2=e.getX();
  41.                 y2=e.getY();
  42.                 x+=(x2-x1);
  43.                 y+=(y2-y1);
  44.                 lb.setLocation(x, y);
  45.                 //System.out.println(x2+" "+y2);
  46.         }
  47.         public void mouseMoved(MouseEvent e){}
  48.         public static void main(String[] args) {
  49.                 new Ch100();
  50.         }
  51. }
複製代碼

TOP

返回列表