我初学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.EXIT_ON_CLOSE);
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()
{
all_rectangle = 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 < all_rectangle.size(); i++)
{
g2.draw((Rectangle2D)all_rectangle.get(i));
}
}
public int find(Point2D p)
{
for (int i = 0; i < all_rectangle.size(); i++)
{
if (all_rectangle.get(i).contains(p))
{
return i;
}
}
return -1;
}
public void add_Rect(Point2D p)
{
double x = p.getX();
double y = p.getY();
Rectangle2D s = new Rectangle2D.Double(
x - Rectangle_length / 2,
y - Rectangle_length / 2,
Rectangle_length,
Rectangle_length);
all_rectangle.add(s);
repaint();
}
public void del_Rect(int p)
{
all_rectangle.remove(p);
repaint();
}
private ArrayList<Rectangle2D> all_rectangle;
private static final int Rectangle_length = 10;
private class ML extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
if (find(e.getPoint()) == -1)
{
add_Rect(e.getPoint());
}
}
public void mouseClicked(MouseEvent e)
{
int flag = find(e.getPoint());
if ( e.getClickCount() >= 2 && flag >= 0)
{
del_Rect(flag);
}
}
}
private class MML implements MouseMotionListener
{
public void mouseMoved(MouseEvent e)
{
if (find(e.getPoint()) < 0)
{
setCursor(Cursor.getDefaultCursor());
}
else
{
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}
}
public void mouseDragged(MouseEvent e)
{
int flag = find(e.getPoint());
if (flag >= 0)
{
int x = e.getY();
int y = e.getY();
all_rectangle.get(flag).setFrame(
x - Rectangle_length / 2,
y - Rectangle_length / 2,
Rectangle_length,
Rectangle_length);
repaint();
}
}
}
}