example7_31.java

来自「不错的教程 适合中高级人员的使用」· Java 代码 · 共 63 行

JAVA
63
字号
import java.awt.*;import java.awt.event.*;
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();
   }
   public void mouseEntered(MouseEvent e){}
   
   public void mouseReleased(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;
		   com.setLocation(a-x0,b-y0);	
	   }
   }
}
 
public class Example7_31
{  public static void main(String args[])
   { Win win= new Win();
   }
}

⌨️ 快捷键说明

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