在 JFrame 中获取 JPanel 内的准确坐标

问题描述 投票:0回答:1

如何从放置在 JFrame 中的 JPanel 获取准确的 xy 坐标。

我尝试自己解决这个问题,但坐标略有偏差,我不知道为什么。 我知道这可能不是有效的代码。我仍在学习,只是为了好玩而尝试不同的东西。

我在窗口中使用了鼠标事件将窗口的标题更改为鼠标的坐标。 总体目标是让我更容易获得我想要放置组件的位置的 xy 坐标。

尽管不需要它,但也为矩形创建了一个内部类,因为我想尝试一下内部类。 我不确定这是否是造成混乱的原因。

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import javax.swing.*

public class GetCoordinates extends JFrame {
    private Dimension size;

    public GetCoordinates(int x, int y) {
        size = new Dimension(x, y);

        setTitle("Click to get coordinates");
        setSize(size);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel windowPane = new JPanel();

        windowPane.addMouseListener(new MouseAdapter() {     
            @Override
            public void mouseClicked(MouseEvent e) {

                int x = e.getX();
                int y = e.getY();
                
                setTitle(String.format("x: %s, y: %s", x, y));
            }
        });
        GetCoordinates.Rect rectangle = new GetCoordinates.Rect(100, 100);
        windowPane.add(rectangle);
        add(windowPane);
    }
  
    public class Rect extends JComponent {
        private int x, y;
        private final int SIZE = 50;
        
        public Rect(int x, int y) {
            this.x = x;
            this.y = y;
            
            setPreferredSize(size);
        }
        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            
            Rectangle2D.Double r = new Rectangle2D.Double(x, y, SIZE, SIZE);
            g2d.setColor(Color.BLUE);
            g2d.fill(r);
        }
    }
    public static void main(String[] args) {
        GetCoordinates gc = new GetCoordinates(640, 480);
        gc.setVisible(true);
    }
}

java swing jframe jpanel jcomponent
1个回答
0
投票

获取组件的鼠标位置将提供相对于组件左上角位置的坐标。如果您询问容器的位置,您可能会得到同一点的不同坐标,并且这会一直持续到根。

如果要将坐标从一个组件转换到另一个组件,最好通过绝对坐标(屏幕)。有一些方法可以帮助您:

© www.soinside.com 2019 - 2024. All rights reserved.