testmouse.java

来自「学习java语言」· Java 代码 · 共 66 行

JAVA
66
字号
import java.awt.*;
import java.awt.event.*;
import javax.swing.SwingUtilities;
class Win extends Frame implements MouseListener, MouseMotionListener {
  Button button;
  TextField text;
  int x, y,a,b,x0,y0;
 
  Win() {
    button = new Button("用鼠标拖动我");
    text = new TextField("用鼠标拖动我", 8);
    button.addMouseListener(this);
    button.addMouseMotionListener(this);
    text.addMouseListener(this);
    text.addMouseMotionListener(this);
    addMouseMotionListener(this);
    setLayout(new FlowLayout());
    add(button);
    add(text);
    addWindowListener(new WindowAdapter() {
                         public void windowClosing(WindowEvent e) {
                            System.exit(0);
                         }
                      });
    setBounds(10,10,350,300);
    setVisible(true);
    validate();
  }
  public void mousePressed(MouseEvent e) {
  	Component com = null;
  	com = (Component)e.getSource();
  	a = com.getBounds().x;
  	b = com.getBounds().y;
  	x0 = e.getX();
  	y0 = e.getY();
  	System.out.println(a+" "+b+" "+x0+" "+y0);
  
  }
  public void mouseReleased(MouseEvent e) {}
  public void mouseEntered(MouseEvent e) {}
  public void mouseExited(MouseEvent e) {}
  public void mouseClicked(MouseEvent e) {}
  public void mouseMoved(MouseEvent e) {}
  public void mouseDragged(MouseEvent e) {
    Component com = null;
    if(e.getSource() instanceof Component) {
      com = (Component)e.getSource();
      a = com.getBounds().x;
      b = com.getBounds().y;
      x = e.getX();
      y = e.getY();
      a = a + x;
      b = b + y;
      System.out.println(a+" "+b+" "+x+" "+y);
      com.setLocation(a-x0,b-y0);
      
    }
  }
}
public class TestMouse {
   public static void main(String[] args) {
     new Win();
   }
}                   
                        
                        

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?