java获取组件位置,在Java中获取组件的坐标

博客讲述了如何在Java Swing中准确获取JInternalFrame的内容面板相对于JLayeredPane的边界坐标,强调了需要考虑边框、标题栏等因素。通过SwingUtilities的convertRectangle方法进行坐标转换来补偿这些因素的影响。
摘要由CSDN通过智能技术生成

I have a JLayeredPane, and inside the JLayeredPane is a JInternalFrame. What I need are the bounds (x position, y position, width, height) of the content pane in the JInternalFrame. The bounds need to be in relation to the JLayeredPane. My problem is the borders, title bar, and I'm not sure what else of the JInternalFrame are messing with my calculation. It's a few pixels off.

Here is how I try to calculate it. This code is in the JInternalFrame:

Rectangle area = new Rectangle(

getX() + 2, //The x coordinate of the JInternalFrame + 2 for the border

getY() + ((javax.swing.plaf.basic.BasicInternalFrameUI) getUI()).getNorthPane().getHeight(), //The Y position of the JinternalFrame + theheight of the title bar of the JInternalFrame

getContentPane().getWidth() - 2, //The width of the Jinternals content pane - the border of the frame

getContentPane().getHeight() //the height of the JinternalFrames content pane

);

I need to get the location of the content pane of the internal frame.

rybna.png

解决方案

Coordinates with respect to what? The screen? The window?

Calling getLocation() will give you the coordinates relative to the component's parent in the window hierarchy.

SwingUtilities has several methods for transforming coordinates from one frame of reference to another. So, to compensate for the title bar and frame, you can do this:

JInternalFrame iframe = ...

Container c = iframe.getContentPane();

Rectangle r = c.getBounds();

r = SwingUtilities.convertRectangle(c.getParent(), r, iframe.getParent());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值