【问题标题】:Close JFrame but keep executing program关闭 JFrame 但继续执行程序
【发布时间】:2018-08-11 04:36:14
【问题描述】:

我想通过单击关闭按钮关闭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)的情况下彻底销毁类?

【问题讨论】:

  • 你有一个非守护线程正在运行,它使 jvm 保持运行,你需要终止它们。
  • 你“可以”使用 EXIT_ON_CLOSE,但是当第一帧关闭时会终止 jvm - 而且,你的 while 循环可能会导致很多窗口
  • Example of idle dialog with timeout 但更多上下文可能有助于提供更合适的解决方案
  • 谢谢。有没有破坏类的代码? (无螺纹)
  • 我只想指出评论没有意义

标签: java multithreading swing class jframe


【解决方案1】:

这是一个使用 Timer 在一定时间后关闭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);
    }
}

【讨论】:

    猜你喜欢
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多