173day(鼠标事件)

本文介绍了一个使用Java Swing编写的简单图形编辑应用。该应用允许用户通过鼠标操作在画布上放置、移动和删除方块。文章详细展示了如何利用MouseListener和MouseMotionListener监听器来响应用户的鼠标事件。

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

《2018年4月2日》【连续173天】

标题:鼠标事件;

内容:
1.

2.一个简单的图形编辑应用程序,允许用户在画布上放置,删除方块;

 

public class MouseFrame extends JFrame
{
	public MouseFrame()
	{
		add(new MouseComponent());
		pack();
	}

	public static void main(String[] args)
	{
		EventQueue.invokeLater(() ->
		{
			JFrame frame =new MouseFrame();
			frame.setTitle("Action");
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setVisible(true);
		});
	}
}
public class MouseComponent extends JComponent
{
	private static final int DEFAULT_WIDTH =300;
	private static final int DEFAULT_HEIGHT =200;
	
	private static final int SIDELENGTH =10;
	private ArrayList<Rectangle2D>squares;
	private Rectangle2D current;
	
	public MouseComponent()
	{
		squares =new ArrayList<>();
		current = null;
		
		addMouseListener(new MouseHandler());
		addMouseMotionListener(new MouseMotionHandler());
	}
	public Dimension getPreferredSize() {return new Dimension(DEFAULT_WIDTH,DEFAULT_HEIGHT);}
	public void paintComponent(Graphics g)
	{
		Graphics2D g2 =(Graphics2D) g;
		for(Rectangle2D r:squares)
		{
			g2.draw(r);
		}
	}
	public Rectangle2D find(Point2D p)
	{
		for(Rectangle2D r:squares)
		{
			if(r.contains(p)) return r;
		}
		return null;
	}
	public void add(Point2D p)
	{
		double x =p.getX();
		double y =p.getY();
		current =new Rectangle2D.Double(x - SIDELENGTH/2,y - SIDELENGTH/2,SIDELENGTH,SIDELENGTH );
		squares.add(current);
		repaint();
	}
	public void remove(Rectangle2D s)
	{
		if(s==null)return ;
		if(s==current)current =null;
		squares.remove(s);
		repaint();
	}
	private class MouseHandler extends MouseAdapter
	{
		public void mousePressed(MouseEvent event)
		{
			current =find(event.getPoint());
			if(current ==null)add(event.getPoint());
		}
		
		public void mouseClicked(MouseEvent event)
		{
			current =find(event.getPoint());
			if(current!=null && event.getClickCount() >= 2)remove(current);
		}
	}
	private class MouseMotionHandler implements MouseMotionListener
	{
		public void mouseMoved(MouseEvent event)
		{
			if(find(event.getPoint()) ==null)setCursor(Cursor.getDefaultCursor());
			else setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
		}
		public void mouseDragged(MouseEvent event)
		{
			if(current!=null)
			{
				int x =event.getX();
				int y =event.getY();
				current =new Rectangle2D.Double(x - SIDELENGTH/2,y - SIDELENGTH/2,SIDELENGTH,SIDELENGTH );
				repaint();
			}
		}
	}
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值