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;
}
}
swing中隐藏光标, XOR模式绘图
最新推荐文章于 2021-01-17 14:43:00 发布