组件坐标

时间:2012-08-21 19:38:53

标签: java swing point mouse-listeners swingutilities

我正在尝试获取与其父级相关的组件坐标。例如,当我有一个 500x500 JFrame ,其中有一个孩子 - JPanel - 在 [50,10] < / em>我应该得到 [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)

1 个答案:

答案 0 :(得分:5)

试试这个:

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

使用的isnatead(在提供的代码段中至少从未使用过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));

编辑:

如果我明白你想要什么,那么为什么还要烦恼所有的代码呢?在每个JPanel s MouseListener的{​​{1}}执行此操作:

mouseClicked()