从另一个类中处理 JFrame
如何从另一个类中处理 JFrame
?我的代码如下所示。
public class MainWindow
{
JFrame main_f = new JFrame("xx");
main_f.getContentPane().setLayout(new BorderLayout());
main_f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
.
.
.
}
处置类:
public static void DisposingJFrame (){
.
.
.
MainWindow.main_f.dispose();
}
MainWindow.main_f.dispose()
将不起作用,因为 main_f
不是变量。你能帮助我吗?
How can I dispose JFrame
from another class? My code is listed below.
public class MainWindow
{
JFrame main_f = new JFrame("xx");
main_f.getContentPane().setLayout(new BorderLayout());
main_f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
.
.
.
}
Disposing class:
public static void DisposingJFrame (){
.
.
.
MainWindow.main_f.dispose();
}
MainWindow.main_f.dispose()
won't work because main_f
isn't a variable. Can you help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
建议:
将
JFrame
实例设为MainWindow
类的字段,并提供访问器 em> 方法。然后在
Dispose
类中,您应该有一个MainWindow
实例,您只需执行以下操作即可处置其JFrame
实例:建议:
编辑:
这是为了解决您看到的错误:
关于第一个错误,这是因为在我提供的示例中,我使用了
final
修饰符。该字段必须在对象创建时初始化。因此,您必须有多个构造函数。要解决此问题,请删除final
修饰符,或在MainWindow
的每个构造函数中初始化main_f
字段。关于第二个错误,
mainWindowInstance
是我留给你创建的东西。这是一个“例子”——Suggestion:
Make the
JFrame
instance a field of theMainWindow
class, and provide an accessor method for it.And then in the
Disposing
class, you should have aMainWindow
instance, where you'll simply do the following to dispose of itsJFrame
instance:Recommendation:
Edit:
This is to address the errors that you're seeing:
With regard to the first error, this is because in the example I provided, I used the
final
modifier. This field must be initialized upon object creation. Therefore, you must have more than one constructor. To resolve this, either remove thefinal
modifier, or initialize themain_f
field in every constructor ofMainWindow
.With regard to the second error,
mainWindowInstance
is something that I left for you to create. Here's a "for instance" -如果你想像这样访问它,你需要将 main_f 设为静态变量。
但是,这是非对象模式。相反,这样做:
另一种方法是给 DisusingJFrame MainWindow 的实例(就像这样 ) ,您不需要将 MainFrame 声明为单例)
you need to make main_f to be a static variable if you want to access it like this.
BUT, this is non object pattern. Instead of that, do this :
Another way is to give to DisposingJFrame the instance of MainWindow (like that, you don't need to declare MainFrame as a singleton)
有一个最简单的方法可以做到这一点。从另一个类处置一个类的JFrame的Java代码如下:
There is a simplest way of doing this. The Java code for disposing the JFrame of a class from another class is as follows: