要求:
编写应用程序,拖动图片到目标区域,使之重合,并给出重合提示显示,
如图:
代码:
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);
}
}
}