【问题标题】:Can findComponentAt() work before a JComponent is painted?findComponentAt() 可以在绘制 JComponent 之前工作吗?
【发布时间】:2010-10-29 03:00:23
【问题描述】:

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

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

为此,我创建了一个与显示的 JComponent 相同的 JComponent,并使用鼠标 x 和 y 值询问 findComponentAt() 以获取正确的组件。这不是很好。如果我为节点重用 JComponents,如果我尝试为与最后绘制的节点大小不同的节点获取工具提示,就会感到困惑。如果我在计算工具提示时为每个节点创建一个新的 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);

componentTop 作为根 JComponent 返回,无论它传递什么 x 和 y 值。

那么是否有可能让 Swing 正确计算 JComponent 的大小和位置而无需实际绘制它们?

【问题讨论】:

    标签: java swing


    【解决方案1】:

    您在图表中有组件的图像,它们必须具有它们的大小才能正确绘制。

    要找到您的“印章”,您应该在图表中倒退(按 z 顺序)并找到您的鼠标位置落入的第一个图像。

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

    【讨论】:

    • 问题不在于找到正确的节点。我有这个。问题是在节点中获取子组件。我希望在同一个节点中显示不同的工具提示,具体取决于鼠标是在标签还是图像上。
    【解决方案2】:

    我自己找到了答案。关键问题是 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(也使用此 Renderer 模式)中查找子组件。

    【讨论】:

      猜你喜欢
      • 2013-11-30
      • 2012-01-21
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2013-03-28
      • 1970-01-01
      相关资源
      最近更新 更多