关闭JFrame,但继续执行程序

时间:2018-08-11 04:36:15

标签: java multithreading swing class jframe

我想通过单击关闭按钮来关闭JFrame。框架已关闭,但Window相关类仍在运行。

如何关闭框架以使整个班级停止?

public class Game {

public Game2() throws InterruptedException, IOException {        
        new TimerDemo(30,2);
        while (flag) {
            play();
        }
    }
private void play() throws InterruptedException, IOException {

        NewJFrame fr = new NewJFrame();
        fr.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        fr.addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent e) {     
                e.getWindow().dispose();
                System.out.println("JFrame Closed!");
            }
        });
    }
}

TimerDemo(30,2)中,必须在30秒后停止play()

如何在不使用System.exit(0)的情况下彻底破坏类?

1 个答案:

答案 0 :(得分:0)

下面是使用计时器在一定时间后关闭Jframe(在这种情况下)的示例:

import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.Timer;

public class DelayedCloseWindow extends JFrame {

    private JLabel counter;
    private int seconds;
    public DelayedCloseWindow(int seconds)  {

        this.seconds = seconds;
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        counter = new JLabel(String.valueOf(seconds));
        counter.setHorizontalAlignment(SwingConstants.CENTER);
        add(counter, BorderLayout.NORTH);
        JButton button = new JButton("Close");
        button.addActionListener(a -> startCountDown());
        add(button, BorderLayout.SOUTH);
        pack();
        setVisible(true);
    }

    private void startCountDown() {
        new Timer(1000, e  -> countDown() ).start();
    }

    private void countDown() {

        if( seconds > 1) {
            counter.setText(String.valueOf(seconds--));
        } else { // time is over
            dispose();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new DelayedCloseWindow(30);
    }
}