2014-10-02 96 views
0

我有一個處理某些文件的程序。有時候,我需要在處理過程中阻止它,但是在如何完成這個過程中遇到困難。我已經看到了幾種可能性,但我不確定要追求什麼。多線程,就像在遊戲中一樣嗎?我發現了一些關於取消的信息,但它似乎只適用於數據輸入過程中?我在下面包括我的GUI的代碼,也許我只是做了錯誤的事情?如何安全地退出Swing應用程序

需要明確的是,我們的目標是停止程序,無論它在哪裏處理?

private JRadioButton blockButton, unblockButton; 
private JButton btnCancel; 
private ButtonGroup group; 
private JLabel text; 
private JButton enter; 

public Gui(){ 
    super("Download CORS files"); 
    setLayout(null); 

    text = new JLabel("Would you like to download data in a block of days or intermittently over time?"); 
    add(text); 

    blockButton = new JRadioButton("Block of Days", true); 
    unblockButton = new JRadioButton("Intermittent Days", false); 
    btnCancel = new JButton("Cancel run"); 
    add(blockButton); 
    add(unblockButton); 
    add(btnCancel); 

    group = new ButtonGroup(); 
    group.add(blockButton); 
    group.add(unblockButton); 

    // Get the size of the screen 
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); 
    // Determine the new location of the window 
    int w = this.getSize().width; 
    int h = this.getSize().height; 
    int x = ((dim.width-w)/2)-200; 
    int y = ((dim.height-h)/2)-200; 
    // Move the window 
    this.setLocation(x, y); 

    enter = new JButton("Enter"); 
    enter.addActionListener(this); 
    add(enter); 

    text.setBounds(5,5,700,25); 
    blockButton.setBounds(5, 25, 300, 25); 
    unblockButton.setBounds(5,50, 300, 25); 
    enter.setBounds(75,100,100,20); 
    btnCancel.setBounds(300,100,100,20); 

    btnCancel.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      System.exit(0); 
     }}); 
+5

調用'System.exit(1);'。這將阻止它。 – 2014-10-02 15:54:44

+1

如果您試圖從一個Swing窗口終止一個選項,那不是線程安全的。您需要設置一個任務,以允許Swing的功能正常工作。 – Compass 2014-10-02 15:56:16

+2

http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#exit(int) – StackFlowed 2014-10-02 15:56:23

回答

0

兩種方式停止處理,視情況而定

  1. 停止處理I/O:如果您需要擺脫I/O進程,IMO最好的辦法是關閉Stream,特別是Reader線程。您可能會拋出IOException異常,但這是異常情況的例外情況
  2. 激烈的計算/處理:如果您想停止激烈的處理循環,則應該在處理Thread上調用Thread.interrupt()。如果您已經編寫了處理代碼,則可以檢查循環/代碼中某處的Thread.interrupted()狀態。另一方面,如果您使用的是第三方代碼,這可能會也可能不會工作
+0

因此,Thread.interrupt()是否可以按下按鈕的形式工作,這會停止程序的處理和關閉?我並不擔心I/O,但真正從沒有任務管理器的情況下停止處理。也許這是一個完全可以接受的方法,但僅僅依靠這種方法感覺不對。 – Iakona 2014-10-03 16:52:35

+0

是的,你可以通過點擊按鈕的動作來實現這一點 – ControlAltDel 2014-10-03 17:08:11

+0

我不明白你的評論的最後一句話。你能澄清嗎? – ControlAltDel 2014-10-03 17:08:56