大致的情况为,点击一个炮塔,然后这个炮塔跟着鼠辈移动到目标地点,然后点击放下这个炮塔。
原理为,点击炮塔为监测鼠标点击事件,是否点中这个炮塔,如果点中,那么复制一个炮塔,随着鼠标在窗体上移动。
package com.javaer.examples.awt;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* 随着鼠标走动的图片
*
* @author mc2
*
*/
public class MoveImageMouse {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ToJFrame jframe = new ToJFrame();
jframe.setSize(500, 500);
jframe.setLocation(150, 150);
jframe.setTitle("鼠标放在图片上,点击不放并移动,图片也会移动哦!");
jframe.setResizable(false);
jframe.setVisible(true);
}
}
class ToJFrame extends JFrame implements MouseMotionListener, MouseListener {
private static final long serialVersionUID = -3236102177939994100L;
private JLabel testTxt;
private JLabel image;
JLabel image2;
private int x = 160;
private int y = 20;
private int a;
private int b;
private int isSelect = 0;// 释放选择了一个炮塔
public ToJFrame() {
Container contentPane = this.getContentPane();
contentPane.setLayout(null);
// contentPane.setBackground(Color.WHITE);
testTxt = new JLabel();
image = new JLabel(
new ImageIcon(ToJFrame.class.getResource("tan1.gif")));
image.setBounds(x, y, 40, 40);
// image.addMouseMotionListener(this);
// image.addMouseListener(this);
this.addMouseMotionListener(this);
this.addMouseListener(this);
contentPane.add(image);
testTxt.setText("aaaaaaa");
testTxt.setBounds(0, 0, 100, 100);
contentPane.add(testTxt);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
// 得到鼠标点下时的坐标
a = e.getX();
b = e.getY();
/*
* MouseEvent.BUTTON1 代表左键, MouseEvent.BUTTON3 代表右键。假如你的鼠标有三个
* 键的话,MouseEvent.BUTTON2 代表中间的键。
*/
// 放下一个防守塔
if (e.getButton() == MouseEvent.BUTTON1 && isSelect == 1) {
System.out.println("释放了图片");
isSelect = 0;
}
// 是否点了一个塔
if (e.getButton() == MouseEvent.BUTTON1 && isSelect == 0) {
if (a > 160 && a < 200 && b > 43 && b < 83) {// 窗体高度移动的过程,发现高了23个像素。所以b界限这里为43和83.
System.out.println("点上了图片");
image2 = new JLabel(new ImageIcon(
ToJFrame.class.getResource("tan1.gif")));
this.add(image2);
isSelect = 1;
}
}
}
public void mouseReleased(MouseEvent e) {
// System.out.println("释放鼠标");
}
// 鼠标不要放,随着鼠标移动
public void mouseDragged(MouseEvent e) {
// 得到鼠标移动时的坐标
// testTxt.setText("a" + x + " : b " + y);
}
public void mouseMoved(MouseEvent e) {
testTxt.setText("a" + e.getX() + " : b " + e.getY());
int c = e.getX() - a;
int d = e.getY() - b;
// 改变图片的位置
x = x + c;
y = y + d;
if (isSelect != 0) {
//新的塔,摆放的位置
image2.setBounds(e.getX() - 20, e.getY() - 23 - 20, 40, 40);
}
}
}