有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java获取面板的坐标

使用mouseevents,我可以获得框架的x和y坐标,但我无法获得面板的x和y坐标。下面的代码是我得到的x和y坐标的框架

public void mouseMoved(MouseEvent e) {
    x = e.getX();
    y = e.getY();
    text = Integer.toString(x) +","+Integer.toString(y);

    Frame.frame.repaint();

}

下面的代码是我试图获得面板的x和y坐标,但它画出了0。油漆油漆是我的jpanel的名字。我不知道我做错了什么。如果可以的话,请帮忙

public void mouseMoved(MouseEvent e) {
    x = Paint.paint.getX();
    y = Paint.paint.getY();
    text = Integer.toString(x) +","+Integer.toString(y);

    Frame.frame.repaint();

}

共 (1) 个答案

  1. # 1 楼答案

    如果我没记错的话,你的MouseListener是在JFrame中注册的,你希望得到相对于JFrame中包含的JPanel的x/y。MouseEvent中的x和y指的是MouseListener注册的组件。如果在父容器上注册了一个MouseListener,并且要获取MouseEvent相对于子组件的坐标,可以使用SwingUtilities转换坐标

    public void mousePressed(MouseEvent e){
        Point childCoordinate = SwingUtilities.convertPoint(parent, e.getPoint(), child);
    }