简体   繁体   中英

How to close JFrame while operation is still in progress

In my swings windows application after click the run button some operation is executed. If i am try to close window when operation is still in progress, close operation is not working. After complete the execution of process then only close window operation is working. Otherwise it will not responds the close operations.

I have already tried below mentioned codes. But that one is not stopped working

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);
        }
    });

If I am clicking close button, my window terminate the currently executed process and Close the window.

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

Then in your actionPerformed method on your JButton actionlistener you just start the thread :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM