我在一个俄罗斯方块游戏程序中看到如下一段代码,对main中的流程有点疑问:
public class Tetris extends JFrame {
public static void main(String[] args) {
Tetris frame = new Tetris();
JMenuBar menu = new JMenuBar();
frame.setJMenuBar(menu);
JMenu game = new JMenu("游戏");
JMenuItem newgame = game.add("新游戏");
JMenu help = new JMenu("帮助");
JMenuItem about = help.add("关于");
menu.add(game);
menu.add(help);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(440, 550);
frame.setTitle("Tetris内测版");
// frame.setUndecorated(true);
frame.setVisible(true);
frame.setResizable(false);
}
}
我的疑问是,在main中,创建完frame后,main函数很快就退出了,那么程序是不是也会退出呢?但是看样子程序并没有退出,那么main函数退出代表什么意思呢?
------解决方案--------------------
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
下面是文档中的解释
setDefaultCloseOperation
public void setDefaultCloseOperation(int operation)
Sets the operation that will happen by default when the user initiates a "close" on this frame. You must specify one of the following choices:
DO_NOTHING_ON_CLOSE (defined in WindowConstants): Don't do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object.
HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the frame after invoking any registered WindowListener objects.
DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and dispose the frame after invoking any registered WindowListener objects.
EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this only in applications.
The value is set to HIDE_ON_CLOSE by default. Changes to the value of this property cause the firing of a property change event, with property name "defaultCloseOperation".
这句话EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method.
调用系统默认的exit方法,当你点关闭按钮的时候才退出main函数,否则程序就会一直都在运行,不知道我的解释对不对,多看看文档里面的解释,你就会更加明白怎么回事了
------解决方案--------------------
一个程序中,一般都有至少一个线程,这个线程就是main线程,它是后台线程,也是守护线程,在其他线程结束后,才结束。
------解决方案--------------------
明白了就结贴哦