Java 在绘制JComponent之前findComponentAt()可以工作吗?

Java 在绘制JComponent之前findComponentAt()可以工作吗?,java,swing,Java,Swing,我正在开发一个GUI,其中JComponents被“标记”在屏幕上。换句话说,不显示实际组件,而是显示组件的图像。这是一个图,其中图的节点是定制的Swing组件,或者更确切地说是Swing组件的标记图像 现在,我想显示节点中特定组件的工具提示 为此,我创建了一个与显示的JComponent相同的JComponent,并使用鼠标x和y值,向findComponentAt()询问正确的组件。这不太管用。如果我为节点重用JComponents,那么如果我试图为一个与上次绘制的节点大小不同的节点获取工具

我正在开发一个GUI,其中JComponents被“标记”在屏幕上。换句话说,不显示实际组件,而是显示组件的图像。这是一个图,其中图的节点是定制的Swing组件,或者更确切地说是Swing组件的标记图像

现在,我想显示节点中特定组件的工具提示

为此,我创建了一个与显示的JComponent相同的JComponent,并使用鼠标x和y值,向findComponentAt()询问正确的组件。这不太管用。如果我为节点重用JComponents,那么如果我试图为一个与上次绘制的节点大小不同的节点获取工具提示,就会感到困惑。如果我为每个节点创建一个新的JComponent,并在计算工具提示时创建一个新的JComponent,则新组件的初始大小为0,0。我可以使用getPreferredSize()计算设置大小,但这仍然不起作用。根JComponent(一个JPanel)的大小合适,但它的子元素都没有大小

工具提示计算代码示例:

// Get a component that matches the stamped component
JComponent nodeComponent = getNodeComponent();

// These next two lines get the size right      
nodeComponent.setSize(nodeComponent.getPreferredSize());
nodeComponent.revalidate();

Component componentTop = nodeComponent.findComponentAt(relativeX, relativeY);
不管传递的x和y值是多少,componentTop都返回为根JComponent


那么,是否可以让Swing在不实际绘制组件的情况下正确计算组件的大小和位置呢?

在图形中有组件的图像,它们必须有其大小才能正确绘制

要找到你的“图章”,你应该在你的图形中向后走(按z顺序),找到你的鼠标位置落入的第一个图像


首选尺寸不起作用,我认为你应该依靠“邮票”的尺寸。

我自己找到了答案。关键问题是Swing不希望布局组件,除非该组件具有正确的父级。因此,我将代码更改为:

    parentComponent.add(nodeComponent);

    // Set the node's size and validate it so it's laid out properly
    nodeComponent.setBounds((int)realizer.getX(), (int)realizer.getY(), (int)realizer.getWidth(), (int)realizer.getHeight());

    nodeComponent.validate();

    // Now we can properly find the child component under our mouse
    Component componentTop = nodeComponent.findComponentAt(relativeX, relativeY);

    // Now remove it from the view
    parentComponent.remove(nodeComponent);

这就像一个符咒。您应该能够使用类似的过程在JLists或JTables(也使用此渲染器模式)中查找子组件。

问题不在于查找正确的节点。我有。问题在于获取节点中的子组件。我希望在同一节点中显示不同的工具提示,具体取决于鼠标是在标签上还是在图像上。