gpt4 book ai didi

java - 元件坐标

转载 作者:搜寻专家 更新时间:2023-11-01 02:29:55 24 4
gpt4 key购买 nike

我正在尝试获取组件相对于其父级的坐标。例如,当我有一个大小为 500x500JFrame 时,它有一个子级 - JPanel - 在 [50, 10] 我应该得到 [50, 10] 结果。无论看起来多么容易,我总是得到错误的坐标([0, 0][3, 24])。

这是我的 JPanel 代码:

class MyPanel extends JPanel implements MouseListener { 
private Component parent;
private String strName;

public MyPanel(Component pr, String name, int w, int h) {
super();

parent = pr;
strName = new String(name);

this.setLayout(null);
this.setSize(w, h);
this.setBackground(Color.WHITE);
this.addMouseListener(this);

this.setVisible(true);
}

/* MouseListener implementation */
public void mouseClicked(MouseEvent event) {
int x = event.getX(); int y = event.getY();
Point pnt = new Point(SwingUtilities.convertPoint(this, new Point(0, 0), parent));
System.out.println(strName + ":" + pnt);
}

public void mouseEntered(MouseEvent event) { }

public void mouseExited(MouseEvent event) { }

public void mousePressed(MouseEvent event) { }

public void mouseReleased(MouseEvent event) { }
}

有什么想法吗?

Java binary & source code (*.tar.xz)

最佳答案

试试这个:

Point pnt = new Point(SwingUtilities.convertPoint(this, event.getPoint(), parent));

isnatead of using(BTW 至少在提供的代码段中从未使用过):

    int x = event.getX();
int y = event.getY();

你不应该这样做:

Point pnt = new Point(SwingUtilities.convertPoint(this, new Point(0,0), parent));

否则返回的坐标将始终相对于 (0,0)。

你也可以这样做(我想你会这样做但是忘记了 x 和 y :P):

    int x = event.getX();
int y = event.getY();
Point pnt = new Point(SwingUtilities.convertPoint(this,
new Point(x,y), parent));

编辑:

如果我明白你想要什么,那为什么还要费心编写那些代码呢?在每个 JPanelMouseListenermouseClicked() 中执行此操作:

public void mouseClicked(MouseEvent event) {
System.out.println(this.getX()+" "+this.getY());//print x and why co-ords for MyJpanel
}

关于java - 元件坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12061860/

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