2017-05-13 15 views
0

我正在構建一個文本編輯器,我不知道如何處理Swing退出按鈕上的偵聽器,該按鈕是自動創建的。 我想在用戶沒有保存文件時使用對話框,例如按下退出按鈕。處理自動創建的退出按鈕?

+0

歡迎來到SO。這是什麼意思自動創建的?通過GUI構建器?因此,使用GUI構建器來添加一個偵聽器。如果它有一個聽衆 - 編輯它。如果沒有,並且你不能添加 - 你不能使用它。 – c0der

+2

也許他是指Windows,Mac OS或任何操作系統提供的窗口裝飾品? –

+0

你不明白你的意思是什麼樣的退出按鈕。你應該添加一個顯示它的屏幕截圖。 –

回答

0

假設你有你的窗口句柄,假設它是一個Window物體(如JFrame或其他種類的窗口),你可以聽到WindowEvent事件。以下是windowClosed的示例,如果您需要先截取它,則可以用windowClosing替換它。

frame.addWindowListener(new WindowAdapter() { 
     @Override 
     public void windowClosed(WindowEvent e) { 
      // do something here 
     } 
    }); 
0

逐步轉到:

  1. 聲明布爾變量saved和它的默認值設置爲false。
  2. 當用戶保存文件時,將其更改爲true
  3. 當按下退出按鈕時,檢查變量。
  4. 如果true退出,則提示用戶保存文件。

所以,最後這個代碼片段看起來像:

public boolean saved = false; 

saveButton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     saved = true; 
     //Code to save file 
    } 
}); 

exitButton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     if(saved) 
      System.exit(0); 
     else { 
      //Code to prompt user to save file 
     } 
    } 
}); 
+0

我不能添加監聽器退出按鈕,因爲這個按鈕正在自動創建 – thenewproblem

+1

@thenewproblem添加所有重要的信息的問題。不在評論中。這是什麼意思自動創建的?如果它有一個聽衆 - 編輯它。如果沒有,並且你不能添加 - 你不能使用它。 – c0der

1
final JFrame f = new JFrame("Good Location & Size"); 
// make sure the exit operation is correct. 
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); 
f.addWindowListener(new WindowAdapter() { 
    public void windowClosing(WindowEvent we) { 
     // pop the dialog here, and if the user agrees.. 
     System.exit(0); 
    } 
}); 

如在本answer to Best practice for setting JFrame locations,其在退出之前&尺寸串行化幀位置看到。