此代码创建一个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);
}
}}
答案 0 :(得分:2)
我只想在用户点击鼠标时显示点击位置的坐标。
这就是发生的事情。您已将MouseListener添加到面板,因此您可以相对于面板单击鼠标。
如果您希望鼠标相对于框架单击,则需要将MouseListener添加到框架中。
或许你只需要改变:
//g.drawString("(" + x + "," + y + ")", 10, 10);
g.drawString("(" + x + "," + y + ")", x, y);