gpt4 book ai didi

java - 查找子组件相对于其父面板的位置

转载 作者:行者123 更新时间:2023-12-02 14:24:14 25 4
gpt4 key购买 nike

我正在使用 java 程序创建背景图像,并将其上传到站点以用于显示数据。这些图像基于创建独特 View 和数据点的参数,我可以将其上传到服务器。

在网站上,我添加了一些项目以在屏幕上的特定位置显示数据。我已经做到了,这样我的 java 程序就可以创建背景和数据点,但我必须通过找到正确的位置并在运行时配置它们来手动配置数据点的位置。

我想找出我的java程序的父面板中特定标签和面板的相同位置,这样我就可以存储这些点并在以后使用它们来生成我的数据点的位置,以便将来可以自动化.

我的背景结构是这样的

框架 - 包含一个 JTabbedPane,可在 4-10 个不同的面板之间切换。

每个选项卡 Pane 面板都是主面板,它成为背景。

每个面板内都有多个使用 GridbagLayout 组织的子面板。

每个子面板都可以有自己的面板或标签,这些面板或标签是我想要记录的位置。

这是一张显示其中一个面板示例的图片。红色框是我想要获取位置的标签的位置。

Pic

我尝试使用此代码来查找位置并将它们放在标签上,但位置始终位于 0,0

public void positions(Container p1) {

for (Component p : p1.getComponents()) {
if (p instanceof JLabel) {

try {
if (((JLabel) p).getText().isEmpty()) {
Point spot = ((JLabel) p).getLocation();
((JLabel) p).setText(spot.toString());
}
} catch (NullPointerException e) {

}
//System.out.println(e.getMessage());
} else {
if (p instanceof JPanel) {
positions((Container) p);
}
}
}

}

这会在我的更新结束时调用该函数

mainPanel.revalidate();
mainPanel.repaint();
positions(mainPanel);

更新。我从我的框架类调用了上述函数,该类更新选项卡式 Pane 上的每个面板,然后打包它,然后调用该函数。

Output

正如您所看到的,位置是相对于包含标签的面板的,而不是相对于包含所有子面板的面板。

最佳答案

而不是

if (((JLabel) p).getText().isEmpty()) {
Point spot = ((JLabel) p).getLocation();
((JLabel) p).setText(spot.toString());
}

如果您想要相对于主面板的位置,您可能应该这样做:

Point spot = new Point();
Component currComponent = p;
while ( currComponent != null && currComponent != mainPanel ) {

Point relativeLocation = currComponent.getLocation();
spot.translate( relativeLocation.x, relativeLocation.y );
currComponent = currComponent.getParent();
}


((JLabel) p).setText(spot.toString());

这基本上添加了每个 JLabel 的坐标(这是在 if 内)到其所有父级的坐标,一直到 mainPanel .

关于java - 查找子组件相对于其父面板的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35015576/

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