我正处于学习 Java 的初级阶段。 到目前为止,在我阅读的所有文档中,都提到 Java 使用安全引用来访问对象而不是内存指针。 此外,当方法返回时,其局部作用域的变量将符合垃圾收集条件。
那么为什么在下面的代码中,JFrame 对象在 createFrame 方法返回后没有随窗口一起销毁?
import javax.swing.*;
public class HelloJava {
public static void main( String[] args ) {
createFrame();
}
private static void createFrame() {
JFrame frame = new JFrame( "Hello, Java!" );
JLabel label = new JLabel( "Hello, Java!", JLabel.CENTER );
frame.getContentPane().add( label );
frame.setSize( 300, 300 );
frame.setVisible( true );
}
}
不仅窗口可见,我还可以对该窗口执行所有操作,如拖动、最大化、最小化等。
最佳答案
因为 EDT 现在正在运行。
有关详细信息,请参阅 Concurrency in Swing尤其是:
-
In standard programs, there's only one such thread: the thread that invokes the
main
method of the program class. -
Swing event handling code runs on a special thread known as the event dispatch thread. Most code that invokes Swing methods also runs on this thread.
关于java - 为什么 JVM 在其变量超出范围后不销毁 JFrame 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12237444/