Java 2使用教程:事件的处理

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;


class LP extends JLayeredPane implements MouseListener,MouseMotionListener
{
JButton button;
int x,y,a,b,x0,y0;
LP(){
button=new JButton("用鼠标拖动我");
button.addMouseListener(this);
button.addMouseMotionListener(this);
setLayout(new FlowLayout());
add(button,JLayeredPane.DEFAULT_LAYER);
}
public void mousePressed(MouseEvent e){
JComponent com = null;
com = (JComponent)e.getSource();
setLayer(com,JLayeredPane.DRAG_LAYER);
a = com.getBounds().x;
b = com.getBounds().y;
x0 = e.getX();
y0 = e.getY();
}
public void mouseReleased(MouseEvent e){
JComponent com=null;
com = (JComponent)e.getSource();
setLayer(com,JLayeredPane.DEFAULT_LAYER);
}
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;
com.setLocation(a-x0,b-y0);
}
}
}


class WindowMove extends JFrame
{
LP layeredPane;
WindowMove(){
layeredPane = new LP();
add(layeredPane,BorderLayout.CENTER);
setVisible(true);
setBounds(12,12,300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


public class E
{
public static void main(String args[]){
WindowMove win = new WindowMove();
win.setTitle("处理鼠标拖动事件");
win.setBounds(10,10,460,360);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值