从外部类切换 Java 中的 jPanel
我有 jFrame
类 MainForm
,其中包含 main()
、placePanel(panel)
和下拉菜单。从下拉菜单中的项目中,我调用 placePanel(panel)
方法将特定面板放置在 jFrame
容器中。这很好用。
但是,当我单击 jPanel
类中的按钮时,我不知道如何切换面板。当我尝试从加载到 jFrame
的任何 jPanel
调用 jFrame
的 MainForm.placePanel(panel)
时的容器,我收到错误:无法引用非静态内容
等。我也尝试了Mainform.getContainer().add(panel)
,但它没有也工作。
我不知道如何从另一个类访问 MainForm 的容器,或者如何使用另一个面板中的方法切换面板。
谢谢
I have jFrame
class MainForm
which contains main()
, placePanel(panel)
and drop down menu. From the items in drop down menu I call on placePanel(panel)
method to place a specific panel in the jFrame
container. This works fine.
But, I don't know how to switch panels when I click on a button which is inside a jPanel
class. When I try to call jFrame
's MainForm.placePanel(panel)
from any jPanel
which is loaded into jFrame
's container, I get the error: cannot reference non-static content
etc. I also tried Mainform.getContainer().add(panel)
, but it doesn't work too.
I can't figure out how to access MainForm
's container from another class, or how to switch panels with a method from another panel.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想从另一个对象中调用一个对象的方法,您将需要对第一个对象的引用,以便您可以在活动对象本身而不是类上调用该方法(正如您当前正在尝试的那样)做)。解决此问题的一种方法是将保存 JPanel 的类的引用传递给具有按钮的操作侦听器代码的类(可能在后者的构造函数中)。换句话说,您需要将对当前活动且可视化的 MainForm 对象的引用传递到具有按钮的 ActionListener 的类中。
顺便问一下,您是否将 JPanel 替换为 CardLayout?如果没有,我建议您研究一下,因为这通常是最简单的方法。
编辑:
例如,假设您有一个名为 MainForm 的类,它有一个名为 swapJPanels 的公共方法,允许它交换视图,而另一个类 MyPanel 拥有您的 JButton,想要从 MainForm 类调用方法,那么您可以给 MyPanel一个构造函数,它接受 MainForm 参数并允许您将当前 MainForm 对象(类内部的 this)的引用传递到 MyPanel 对象中:
MainForm:
MyPanel:
If you want to call a method on an object from within another object, you're going to need a reference to the first object so you can call the method on the active object itself and not on the class (as you're currently trying to do). One way to solve this is to pass a reference to the class that holds the JPanels to the class that has the button's action listener code, perhaps in the latter's constructor. In other words you'll want to pass a reference to the current active and visualized MainForm object into the class that has the ActionListener for the button.
By the way, are you swapping JPanels with a CardLayout? If not, I suggest you look into it as it's usually the easiest way to do this.
Edit:
For example, say you have a class called MainForm that has a public method called swapJPanels that allows it to swap views, and another class MyPanel that has your JButton that wants to call a method from the MainForm class, then you could give MyPanel a constructor that takes a MainForm parameter and allows you to pass a reference from the current MainForm object (this inside of the class), into the MyPanel object:
MainForm:
MyPanel: