【问题标题】:How to close JFrame while operation is still in progress如何在操作仍在进行时关闭 JFrame
【发布时间】:2019-01-24 10:15:13
【问题描述】:

在我的 Swings Windows 应用程序中,单击运行按钮后会执行一些操作。如果我在操作仍在进行时尝试关闭窗口,则关闭操作不起作用。完成流程执行后,只有关闭窗口操作才有效。否则不会响应关闭操作。

我已经尝试过下面提到的代码。但是那个并没有停止工作

addWindowListener(new WindowAdapter()
 {
   public void windowClosing(WindowEvent we) 
   {
    System.exit(0); 
            or
    System.exit(1);
            or
    setDefaultCloseOperation(EXIT_ON_CLOSE);     
            or
    setDefaultCloseOperation(3);
                or
        dispose();
    }

}); 
    JButton jb = new JButton("Run");        
    add(jb);         
    jb.setBounds(10, 30, 100, 30);        
    setSize(150,150);  
    setLayout(null);  
    setVisible(true); 
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
      System.exit(0);
    }
    });
    jb.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            // some operations . For Example here i'm add 1E5 data,s in my collection object. again i will replace data's places of each element.
            for(int i=0;i<1E5;i++)
            {
                ll.add(i);
            }
            for(int i=0;i<1E5;i++)
            {
                ll.add(1,i);
            }
            for(int i=0;i<1E5;i++)
            {
                ll.add(0,i);
            }
            System.out.println(ll);
        }
    });

如果我点击关闭按钮,我的窗口会终止当前执行的进程并关闭窗口。

【问题讨论】:

标签: java jvm terminate formclosing


【解决方案1】:
class MyThread extends Thread {      
    public void run() {
        // some operations . For Example here i'm add 1E5 data,s in my collection object
        ..
        ..        
    }
}

然后在您的 JButton actionlistener 上的 actionPerformed 方法中,您只需启动线程:

public void actionPerformed(ActionEvent e) {
    new MyThread().start();
}

【讨论】:

  • 虽然一般来说是正确的,但swing 有一个专门为此目的设计的特殊SwingWorker 类,它提供了内置功能,可以在完成后向EventThread 报告并安全地发布中间结果。
  • @Hulk 我完全同意,但是正如 OP 提到的他甚至不熟悉线程我刚刚发布了最简单的解决方案
  • 是的,但这需要自己处理同步等,这可能比使用已经在后台处理其中一些的东西更棘手。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多