代码之家  ›  专栏  ›  技术社区  ›  David Irwin

findComponent()能否在绘制JComponent之前工作?

  •  0
  • David Irwin  · 技术社区  · 17 年前

    我正在开发一个图形用户界面,其中jcomponents被“压印”在屏幕上。换句话说,实际组件不会显示,而是显示组件的图像。这是一个图形,其中图形的节点是自定义的Swing组件——或者更确切地说是Swing组件的冲压图像。

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

    为此,我创建了一个与显示的组件相同的jcomponent,并使用鼠标的x和y值,请求findcomponent()获得正确的组件。这个不太管用。如果我为节点重用JComponents,那么如果我尝试获取一个与上一个绘制的节点大小不同的节点的工具提示,就会感到困惑。如果我为每个节点创建一个新的jcomponent,并在计算工具提示时创建一个新的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);
    

    componenttop返回为根jcomponent,不管传递的是什么x和y值。

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

    2 回复  |  直到 17 年前
        1
  •  0
  •   Eugene Ryzhikov    17 年前

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

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

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

        2
  •  0
  •   David Irwin    17 年前

    我自己找到了答案。关键问题是,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);
    

    这就像一个魅力。您应该能够使用类似的过程在jlist或jtables中查找子组件(它们也使用这个渲染器模式)。