我正在向我的 JFrame 添加一个 Canvas - 或者更确切地说,一个从 Canvas 继承的对象 - 然后我希望从 JFrame 获取该 Canvas 对象,将其转换为从 Canvas 继承的该对象,然后调用一个方法。但是,当我将 Canvas 添加到 JFrame 并检查 getComponents 数组的长度时,它保持不变。我的 Canvas 添加到了哪里?我可以在哪里访问它?
System.out.println(getComponents().length());
add(new OuterSpace());
System.out.println(getComponents().length()); //This length doesn't change after I add the Canvas for some odd reason
[编辑]在将 Canvas 添加到 JFrame 之前我无法调用某个方法,这就是我希望实现此目的的原因。
最佳答案
您的组件将被添加到 contentPane,该 contentPane 通常是一个 JPanel,并且由 JFrame 的 JRootPane 持有一个 JLayeredPane。
更重要的是,正如我之前提到的,不要使用这样的糟糕代码。相反,创建一个 OuterSpace 变量,将您的实例分配给该变量,将该变量添加到 JFrame,然后在您想要访问该实例时使用该变量。
<小时/>请注意,这没有意义:
<小时/>There is a certain method that I cannot call until the Canvas has been added to a JFrame, so that is why I wish to achieve this.
编辑
另请查看:http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html
<小时/>编辑2
你问:
I am getting an error when I do this, because I want to access the bufferstrategy from the canvas, which I cannot do until it's been added to the jframe.
Canvas ?您甚至不应该将 Canvas 对象与 Swing GUI 一起使用。使用 JPanel。我从未使用过 BufferStrategy,因为我通常在 JPanel 的 PaintComponent 方法中进行所有绘图,包括动画。
听起来您正在尝试在渲染组件之前访问类似图形的对象,并且这与创建组件时没有关系。我的建议仍然有效。
关于java - 从 JFrame 访问 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23946358/