从另一个类处理JFrame [英] Disposing JFrame from another class

查看:178
本文介绍了从另一个类处理JFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从另一个类处理 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();

推荐

  • Read the Learning the Java Language tutorial. This is basic OOP.

编辑

这是为了解决您所看到的错误:

This is to address the errors that you're seeing:


  1. 变量main_f可能尚未初始化

  2. 找不到符号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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆