gpt4 book ai didi

java - 在Java中的JFrame上显示鼠标坐标

转载 作者:行者123 更新时间:2023-12-02 04:15:58 25 4
gpt4 key购买 nike

此代码创建一个 Frame 屏幕,并在用户单击 Frame 上的任意位置时生成 mouseEvent。但是,我希望代码在用户单击鼠标按钮时获取光标坐标,而不是仅获取 JFrame 右上角的坐标。我不知道如何实现这一点。任何帮助将不胜感激。

import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Hw2MouseEventController extends JFrame {
public Hw2MouseEventController() {
MouseClkd mouse = new MouseClkd();
setLayout(new GridLayout());
add(mouse);
}

public static void main(String[] args) {
Hw2MouseEventController frame = new Hw2MouseEventController();
frame.setTitle("Mouse Event Controller");
frame.setLocation(450, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(450, 450);
frame.setVisible(true);
}

static class MouseClkd extends JPanel {
private int x;
private int y;

public MouseClkd() {
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
});
}

public void paint(Graphics g) {
super.paint(g);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.white);
g.drawString("(" + x + "," + y + ")", 10, 10);
}
}}

最佳答案

I just want to display coordinates at clicked place when user clicks the mouse.

这就是正在发生的事情。您将 MouseListener 添加到面板中,以便获得相对于面板的鼠标单击。

如果你希望鼠标点击相对于框架,那么你需要将MouseListener添加到框架中。

或者也许您只需要更改:

//g.drawString("(" + x + "," + y + ")", 10, 10);
g.drawString("(" + x + "," + y + ")", x, y);

关于java - 在Java中的JFrame上显示鼠标坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33320400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com