package
org.example;
import
javax.swing.*;
import
java.awt.*;
import
java.awt.image.BufferedImage;
public
class
MousePositionGui {
private
static
Robot robot;
public
static
void
main(String[] args) {
JFrame frame =
new
JFrame(
"获取鼠标位置"
);
JLabel label =
new
JLabel(
"鼠标位置: "
);
frame.setSize(
400
,
200
);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(
new
FlowLayout());
frame.add(label);
frame.setVisible(
true
);
try
{
robot=
new
Robot();
}
catch
(AWTException e) {
throw
new
RuntimeException(e);
}
new
MyThread1(label, frame).run();
}
private
static
void
updateMousePosition(String msg, JLabel label) {
label.setText(msg);
}
private
static
Color getColorAtPoint(Point p) {
BufferedImage screenCapture = robot.createScreenCapture(
new
Rectangle(p.x, p.y,
1
,
1
));
Color color =
new
Color(screenCapture.getRGB(
0
,
0
));
return
color;
}
static
class
MyThread1
extends
Thread {
JLabel label=
null
;
JFrame frame=
null
;
public
MyThread1(JLabel label,JFrame frame) {
this
.label=label;
this
.frame=frame;
}
public
void
run() {
while
(frame.isVisible()) {
try
{
Point location = MouseInfo.getPointerInfo().getLocation();
final
Color color = getColorAtPoint(location);
updateMousePosition(
"<HTML>鼠标位置: x = "
+ location.getX() +
", y = "
+ location.getY()
+
"\n<br>颜色RGB: "
+ color.getRed() +
", "
+ color.getGreen() +
", "
+ color.getBlue()
+
"</HTML>"
,
this
.label);
Thread.sleep(
100
);
}
catch
(InterruptedException e) {
throw
new
RuntimeException(e);
}
}
}
}
}