【发布时间】:2017-09-25 00:35:03
【问题描述】:
每次我尝试将包含所有关键输入的单独类添加到 JFrame 时,Eclipse 都会告诉我这样做:frame.add(frame, new KeyInput());,它会返回错误:
Exception in thread "main" java.lang.IllegalArgumentException: adding container's parent to itself
。我了解此错误及其来源:
frame.add(frame, new KeyInput());
^^^^^
,但是如果我取出框架组件,我会收到错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method add(Component) in the type Container is not applicable for the arguments (KeyInput)
这个我不明白,但要明白要点:Eclipse 发现了一个实际错误。
【问题讨论】:
-
你为什么要自己添加一个组件?我会考虑仔细查看
add方法的API 文档。我还会考虑看看Key Bindings API 作为KeyListener的替代方案,因为它解决了与主要焦点相关的问题 -
@MadProgrammer 正如我所提到的,没有组件,并且框架是我唯一拥有的,我得到一个错误。而且我已经看过 Key Bindings API,但我不知道如何使用它们。
-
问题依然存在,你为什么要给自己添加一个组件?这是没有意义的,正如 Java 所说,这是一个非法操作 - 你读过How to write a key listener吗?
-
我的“一般”建议是退后一步。首先将您的 GUI 基于
JPanel。准备好后,创建JFrame的实例并向其中添加您的 GUI (JPanel) 实例 - 这将简单地解决与直接处理JFrame相关的许多问题 - "并且我已经看过 Key Bindings API,但我不知道如何使用它们” - 所以,这是一个学习的机会,有很多可用的示例,它会阻止你发布新的关于为什么你的KeyListener随机停止工作的问题 -
根本问题是,这不是您将
KeyListener应用于组件的方式
标签: java eclipse swing graphics keylistener