从另一个类处理JFrame [英] Disposing JFrame from another class
问题描述
如何从另一个类处理 JFrame
?我的代码如下所示。
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);
.
.
.
}
处理类:
public static void DisposingJFrame (){
.
.
.
MainWindow.main_f.dispose();
}
MainWindow.main_f.dispose()
将无效,因为 main_f
不是变量。你能帮助我吗?
MainWindow.main_f.dispose()
won't work because main_f
isn't a variable. Can you help me?
推荐答案
建议:
将 JFrame
实例设为 MainWindow
类的字段,并提供一个访问者方法。
Make the JFrame
instance a field of the MainWindow
class, and provide an accessor method for it.
public final class MainWindow{
private final JFrame main_f;
public MainWindow(){
main_f = new JFrame("xx");
main_f.getContentPane().setLayout(new BorderLayout());
main_f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
.
.
.
}
public final JFrame getMainFrame(){
return main_f;
}
.
.
.
}
然后在 Disposing
class,你应该有一个 MainWindow
实例,你只需要执行以下操作来处理它的 JFrame
实例:
And then in the Disposing
class, you should have a MainWindow
instance, where you'll simply do the following to dispose of its JFrame
instance:
mainWindowInstance.getMainFrame().dispose();
推荐:
- 阅读学习Java语言教程。这是基本的OOP。
- Read the Learning the Java Language tutorial. This is basic OOP.
编辑:
这是为了解决您所看到的错误:
This is to address the errors that you're seeing:
- 变量main_f可能尚未初始化
- 找不到符号mainWindowInstance
关于第一个错误,这是因为在我提供的示例中,我使用了 final
修饰符。必须在创建对象时初始化此字段。因此,您必须具有多个构造函数。要解决此问题,请删除 final
修饰符,或者在 main_f
字段> MainWindow 。
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 the final
modifier, or initialize the main_f
field in every constructor of MainWindow
.
关于第二个错误, mainWindowInstance
是我的意思留下 你 来创建。这是一个例如 -
With regard to the second error, mainWindowInstance
is something that I left for you to create. Here's a "for instance" -
public class Disposing{
private MainWindow mainWindowInstance;
public Disposing(){
mainWindowInstance = new MainWindow();
.
.
.
}
public void diposeMainFrame(){
mainWindowInstance.getMainFrame().dispose();
}
}
这篇关于从另一个类处理JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!