java程序设计基础教程第二版: p212-15

import java.awt.*;
import java.awt.event.*;
import javax.swing.SwingUtilities;
public class naixin{
    public static void main(String args[]){
    new FirstWindow("7-31_Fixed");
    }
}
class FirstWindow extends Frame implements MouseListener,MouseMotionListener{
    Button btn1=new Button("Drag me ?!");
    TextField text1=new TextField("Drag me ?!");
    int x,y;
    boolean move=false;
    FirstWindow(String str1){
        super(str1);
        setLayout(new FlowLayout());
        btn1.addMouseListener(this);
        btn1.addMouseMotionListener(this);
        text1.addMouseListener(this);
        text1.addMouseMotionListener(this);
        addMouseMotionListener(this);
        add(btn1);
        add(text1);
        addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
                }
            });

        setBounds(256,142,600,400);
        setVisible(true);
        validate();
        }
    public void mousePressed(MouseEvent mp){}
    public void mouseReleased(MouseEvent mr){
        move=false;
        Component component2=null;
        component2=(Component)mr.getSource();
        Rectangle rect=component2.getBounds();
    if(mr.getSource()==btn1){
        if(rect.intersects(text1.getBounds())){
            text1.setVisible(false);
            }
        else{
            text1.setVisible(true);
            }               
        }
    if(mr.getSource()==text1){
        if(rect.intersects(btn1.getBounds())){
            btn1.setVisible(false);
            }
        else{
            btn1.setVisible(true);
            }   
   
        }
    }
    public void mouseEntered(MouseEvent menter){}
    public void mouseExited(MouseEvent mexit){}
    public void mouseClicked(MouseEvent mc){}
    public void mouseMoved(MouseEvent mm){}
    public void mouseDragged(MouseEvent mDrag){
        Component component1=null;
        if(mDrag.getSource()instanceof Component){
            component1=(Component)mDrag.getSource();
        if(component1!=this)
            move=true;
            mDrag=SwingUtilities.convertMouseEvent(component1,mDrag,this);//转移鼠标Event到窗口
        if(move){
                x=mDrag.getX();
                y=mDrag.getY();
                int w=component1.getSize().width,
                    h=component1.getSize().height;
                component1.setLocation(x-w/2,y-h/2);
               
                }
            }
        }
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值