java - 当鼠标与 Graphics2D 一起移动时,如何显示 X 和 Y 鼠标位置?
问题描述
当鼠标与 Graphics2D 一起移动时,如何显示 X 和 Y 鼠标位置?
我正在尝试在鼠标移动时显示坐标,但我可以使用System.out.println
,我想使用drawString.join("", 10, 5)
。
那我怎么能达到呢?
*这就是我所做的
public class Bell2 extends JPanel {
static JFrame frame=new JFrame();
public Bell() {
}
public void paint(Graphics g){
Graphics2D g2=(Graphics2D)g;
g2.setColor(Color.yellow);
//Here's where I struggle
g2.drawString.join ("mouseX, mouseY, C");
}
public static void main(String[] args) {
frame.setSize(500,300);
frame.setLocation(300,200);
frame.setVisible(true);
frame.setBackground(Color.black);
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Color c = robot.getPixelColor(456,141);
double mouseY=1.0;
double mouseX=1.0;
while(mouseX !=0 || mouseY !=0) {
mouseX = MouseInfo.getPointerInfo().getLocation().getX();
mouseY = MouseInfo.getPointerInfo().getLocation().getY();
System.out.println("x: "+mouseX+" y: "+mouseY+" c: "+c);
}
}
}
解决方案
不确定这是否正是您要查找的内容,但是,如果您想与原始示例保持相当接近,您可以考虑做这样的事情:
public static void main(String[] args) {
frame.setSize(500,300);
frame.setLocation(300,200);
frame.setVisible(true);
frame.setBackground(Color.black);
try {
final Robot robot = new Robot();
handleMouse(robot);
} catch (final AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void handleMouse(final Robot robot) {
int mouseX = 1;
int mouseY = 1;
while (mouseX !=0 || mouseY !=0) {
final Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
mouseX = mouseLocation.x;
mouseY = mouseLocation.y;
final Color currentColor = robot.getPixelColor(mouseX, mouseY);
System.out.println(String.format("x: %d, y: %d, c: %s", mouseX, mouseY, currentColor));
}
}
请注意,每次和都会currentColor
更新;在您的原始代码段中并非如此。mouseX
mouseY
如果您正在查看终端上的输出,需要注意的另一件事 - 颜色只会在保持 <= 255;时才会mouseX
发生变化;mouseY
超出该值,您可能只会看到以下输出:
java.awt.Color[r=255,g=255,b=255]
推荐阅读
- video - FFmpeg 合并来自不同来源的具有不同比特率的两个文件
- magento - Magento 2 Ui 组件:如何为动态行设置可序列化字段
- google-apps-script - 基于脚本的过滤式查询基于列出的条目从另一个工作表中获取数据
- r - 列在 TRUE 值之前重复行值
- java - 系统类是单例、抽象还是什么?
- reactjs - 调用内部方法 onClick
- flutter - 如何更改弹出菜单中的填充?
- python - Scrapy 在尝试抓取 Ajax 调用页面时返回 400 错误
- spring-boot - 如何使用 quickfixj-spring-boot-starter 从服务器捕获执行报告?
- css - CSS-Grid:使未知行数的最后一行取剩余高度