swing中隐藏光标, XOR模式绘图

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;

public class XorModeTest extends JFrame {
	public static void main(String[] args) {
		EventQueue.invokeLater(() -> {
			XorModeTest frame = new XorModeTest();
			frame.setVisible(true);
		});
	}

	XorModeTest() {
		super("XorMode Test");
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setSize(600, 500);
		add(new TestPane());
		setLocationRelativeTo(null);
	}
}

class TestPane extends JPanel {
	Point lstPos;

	TestPane() {
		BufferedImage cursorImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
		setCursor(getToolkit().createCustomCursor(cursorImage, new Point(0, 0), "NullCursor"));

		addMouseMotionListener(new MouseMotionListener() {
			@Override
			public void mouseMoved(MouseEvent e) {
				drawCross(e.getPoint());
			}
			@Override
			public void mouseDragged(MouseEvent e) {
			}
		});
		addMouseListener(new MouseListener() {
			@Override
			public void mouseClicked(MouseEvent e) {

			}

			@Override
			public void mousePressed(MouseEvent e) {

			}

			@Override
			public void mouseReleased(MouseEvent e) {

			}

			@Override
			public void mouseEntered(MouseEvent e) {

			}

			@Override
			public void mouseExited(MouseEvent e) {
				drawCross(null);
			}
		});
	}

	private void drawCross(Point newPos) {
		Graphics g = getGraphics();
		g.setXORMode(getBackground()); // 设为背景色
		if (lstPos != null) {
			g.drawLine(lstPos.x, 0, lstPos.x, getHeight());
			g.drawLine(0, lstPos.y, getWidth(), lstPos.y);
		}
		lstPos = newPos;
		if (lstPos != null) {
			g.drawLine(lstPos.x, 0, lstPos.x, getHeight());
			g.drawLine(0, lstPos.y, getWidth(), lstPos.y);
		}
		g.dispose();
	}


	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g.fillOval(0, 0, getWidth(), getHeight());
		lstPos = null;
	}
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值