java-掌握MouseEvent事件响应的处理方式

本文介绍了一个使用Java实现的图片拖拽匹配应用案例,通过拖动图片到指定区域并判断是否重合,实现简单的图像匹配功能。代码中详细展示了如何处理鼠标拖动事件,包括设置图片和目标区域,以及在图片与目标区域重合时给予反馈。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

要求:
编写应用程序,拖动图片到目标区域,使之重合,并给出重合提示显示,

如图:
在这里插入图片描述
在这里插入图片描述
代码:

	
public class test {
   public static void main(String args[]) {
      WindowMove win=new WindowMove();
      win.setTitle("处理鼠标拖动事件"); 
      win.setBounds(10,10,460,360);
   }
}
import java.awt.*;

import javax.swing.*;
public class WindowMove extends JFrame{
	 LP lp;
	 JLabel text;
	
     WindowMove() {
      lp=new LP();
      text=new JLabel();
      text.setText("请将图片拖到白色区域");
      lp.setJLabel(text);
      text.addMouseListener(lp);
      add(text,BorderLayout.SOUTH);
      add(lp,BorderLayout.CENTER);
      setVisible(true);
      setBounds(12,12,300,300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
  

}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class LP extends JLayeredPane implements MouseListener,MouseMotionListener {
	JLabel picture,area,text;
    int x,y,a,b,x0,y0;
    public void setJLabel(JLabel text) {
    	this.text=text;
    }
   LP() {
	   picture=new JLabel(new ImageIcon("a.jpg")); 
	   area=new JLabel(new ImageIcon("a.png")); 
	   picture.addMouseListener(this);
	   picture.addMouseMotionListener(this);
      setLayout(new FlowLayout());
      picture.setBorder(BorderFactory.createLineBorder(Color.black));
      area.setBorder(BorderFactory.createLineBorder(Color.red));
      add(area,JLayeredPane.DEFAULT_LAYER);
      add(picture,JLayeredPane.DRAG_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.DRAG_LAYER);
      if(picture.getX()==area.getX()&&picture.getY()==area.getY()){
    	  text.setText("ok");
      }
  }
    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);
      }
      
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值