鼠标事件响应有关问题!
鼠标事件响应问题求助!!
我初学java,正在看core java2,看到第8章鼠标事件那节,有个例子,编写一个简单的图形处理编辑器程序,允许用户在画布上放置、移动和擦除小方块,点下鼠标就放置,在方块内双击鼠标就删除,按住鼠标就可拖动小方块(如果鼠标点在小方块内的话),我仿照书中的源程序,做了些小改动(主要修改的find函数),就不能实现删除和拖放功能了,我检查了一天也没发现哪里有问题,郁闷啊,请各位高手帮我看看,谢谢了哈,以下是我的源程序:
/*
/
import java.awt.;
import java.awt.event.;
import java.util.;
import java.awt.geom.;
import javax.swing.;
public class MouseTest
{
public static void main(String[] args)
{
MouseFrame MF = new MouseFrame();
MF.setDefaultCloseOperation(JFrame.EXITONCLOSE);
MF.setVisible(true);
}
}
class MouseFrame extends JFrame
{
public MouseFrame()
{
setTitle("MouseTest");
Container contentPane = getContentPane();
MousePanel SP = new MousePanel();
contentPane.add(SP);
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
setSize(screenWidth/2,screenHeight/2);
setLocation(screenWidth/4,screenHeight/4);
}
}
class MousePanel extends JPanel
{
public MousePanel()
{
allrectangle = new ArrayList<Rectangle2D>();
addMouseListener(new ML());
addMouseMotionListener(new MML());
}
public void paintComponent(Graphics g)
{
super.paintComponents(g);
Graphics2D g2 = (Graphics2D)g;
for (int i = 0; i < allrectangle.size(); i++)
{
g2.draw((Rectangle2D)allrectangle.get(i));
}
}
public int find(Point2D p)
{
for (int i = 0; i < allrectangle.size(); i++)
{
if (allrectangle.get(i).contains(p))
{
return i;
}
}
return -1;
}
public void addRect(Point2D p)
{
double x = p.getX();
double y = p.getY();
Rectangle2D s = new Rectangle2D.Double(
x - Rectanglelength / 2,
y - Rectanglelength / 2,
Rectanglelength,
Rectanglelength);
allrectangle.add(s);
repaint();
}
public void delRect(int p)
{
allrectangle.remove(p);
repaint();
}
private ArrayList<Rectangle2D> allrectangle;
private static final int Rectanglelength = 10;
private class ML extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
if (find(e.getPoint()) == -1)
{
addRect(e.getPoint());
}
}
public void mouseClicked(MouseEvent e)
{
int flag = find(e.getPoint());
if ( e.getClickCount() >= 2 && flag >= 0)
{
delRect(flag);
}
}
}
private class MML implements MouseMotionListener
{
public void mouseMoved(MouseEvent e)
{
if (find(e.getPoint()) < 0)
{
setCursor(Cursor.getDefaultCursor());
}
else
{
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIRCURSOR));
}
}
public void mouseDragged(MouseEvent e)
{
int flag = find(e.getPoint());
if (flag >= 0)
{
int x = e.getY();
int y = e.getY();
allrectangle.get(flag).setFrame(
x - Rectanglelength / 2,
y - Rectanglelength / 2,
Rectanglelength,
Rectangle_length);
repaint();
}
}
}
}