在没有实例的情况下访问“实例”?

时间:2020-10-03 22:27:34

标签: java

因此,我正在考虑创建一个JFrame而不创建它的实例。

这是我通常的做法:

package framecanvasagain;

public class Framecanvasagain {

    public MyFrame theframe;

    public static void main(String[] args) {
        //creates the frame normally
        theframe = new MyFrame();

        //now let's say I want to access the frame again later on
        theframe.setLocationRelativeTo(null);
    }
    
}

我可以创建一个JFrame而无需创建它的实例,但是以后有没有办法访问该JFrame

package framecanvasagain;

public class Framecanvasagain {

    public static void main(String[] args) {
        new MyFrame(); //Netbeans says "New Instance Ignored" but it still loads a JFrame

        //now let's say I want to access the frame again later on
        MyFrame().setLocationRelativeTo(null); //this returns an error, "cannot find symbol"
    }
    
}

3 个答案:

答案 0 :(得分:1)

简单的答案是否定的。您需要将其设置为变量,以便再次访问其属性。

 new MyFrame(); 

创建JFrame的实例,但Java垃圾收集器会立即将其选中,因为它没有设置任何内容。

您可以这样做:

(new MyFrame()).setLocationRelativeTo(null);

但是,您仍将创建它的实例,并且将无法再次访问其属性。没有创建对象然后将其存储在Java中,就无法重用对象。面向对象编程语言的风险。

将其制成单例可能是另一种选择。

https://www.geeksforgeeks.org/singleton-class-java/

尽管如此,我认为这并不是您真正想做的。

答案 1 :(得分:1)

您的问题标题不正确:

您实际上要问的是: 我可以访问不带实例的实例吗?

答案是:不,你不能!

在示例代码中,您执行创建了JFrame的实例,但是您立即丢弃了对该引用的引用,因此无法解决该特定实例。

此外,它随时都可能被垃圾回收(除非库的某些内部部分也对此有引用,我不是AWT内部专家),所以您的框架可能会随机消失。

但是真正的问题是:您想要在这里实现什么?

答案 2 :(得分:0)

您只需添加一个单词即可完成您要的内容... static。只需将您的myFrame变量static设置为即可。这是您的第一个示例,做了一些修改。我将“以后做”调用移到了另一种方法中,以强调您可以从任何位置访问MyFrame的观点:

package framecanvasagain;

public class Framecanvasagain {

    public static MyFrame theframe;

    public void someOtherMethod() {
        //now let's say I want to access the frame again later on
        Framecanvasagain.theframe.setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        //creates the frame normally
        theframe = new MyFrame();

        ....

    }
}
相关问题