为什么我的组件是 JRootPane 的一个实例,如果我从未将其分配给一个实例?

Why is my component an instance of JRootPane if I never assigned it to one?

让我解释一下我的代码的作用: 我创建了自己的 class,它扩展了 JDialog。这个class,姑且称之为class A,包含:JMenuBar、JMenu、JMenuItem、JButton、JDialog、JPanel和MouseAdapter。我的项目与 FreeCell Game 非常相似,我目前正在尝试移动多个图像,这些图像位于它们自己的 JPanel 中。 现在,我的问题是:当用户点击屏幕上的某些内容时,我会协调他们点击的位置并设置一个组件,例如

Component component = getComponentAt(point);

然后我检查它是否是 JPanel 的实例,即卡片

if (component instanceof JPanel)

所以我可以移动卡片。这就是我的问题出现的地方。当我打印出我的组件 class 是什么时,它表明它是一个 JRootPane,但我一生中从未使用或见过这个对象,直到我刚才查找它。我想知道为什么我的组件是 JRootPane 的对象,而我从未使用过它。

无论我在屏幕上的哪个位置点击,它一直显示我的组件是一个 JRootPane...

是不是因为JRootPane中包含了JDialog? https://docs.oracle.com/javase/7/docs/api/javax/swing/JRootPane.html

It it be because JRootPane contains JDialog?

否 JRootPane 不包含 JDialog。 JDialog 包含 JRootPanel。

I would like to know why my component is an object of JRootPane when I never used use it.

Component component = getComponentAt(point);

那么getComponentAt(...)指的是什么Container呢?是对话框还是面板?

在您的情况下,getComonentAt() 方法似乎是相对于对话框的,因此 return 组件是相对于对话框的。由于添加到对话框的第一个组件是 JRootPane,它 return 是根窗格。

您要做的是将 MouseListener 添加到包含图像的面板。然后在你做的 MouseListener 代码中:

@Override
public void mousePressed(MouseEvent e)
{
    Component parent = e.getComponent();  
    Component child = parent.getComponentAt(...);
}

然后,如果您单击包含图像的组件,您将获得该组件。