2013-03-13 72 views

回答

1

假設你正在使用的Java Swing:

JFrame frame = new JFrame(); 
    frame.setTitle("Project Planner"); 
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); 
    frame.addWindowListener(new WindowAdapter() { 
     @Override 
     public void windowClosing(WindowEvent event) { 
      exitProcedure(); 
     } 
    }); 

public void exitProcedure() { 
    frame.dispose(); 
    System.exit(0); 
} 

只需在dispose方法之前添加想要執行的操作即可。

0

在GUI的addWindowListener()方法中嘗試執行WindowAdapter

0

爲此,您需要將WindowListener註冊到關聯的JFrame。並覆蓋windowClosing()方法。

EDIT
用於隨機選擇一個字符串出字符串數組的可以使用java.util.Random API。對於實施例在這裏是每個JFrame關閉時間的String陣列,並且,一個String隨機挑出出這個陣列的並用方法callMeBeforeExit印刷。

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.SwingUtilities; 
import java.awt.event.WindowEvent; 
import java.awt.event.WindowAdapter; 
import java.awt.BorderLayout; 
import java.util.Random; 
class WorkBeforeClose extends JFrame 
{ 
    String[] strings = { 
          "Hello", 
          "World", 
          "Java", 
          "OOPs" 
         }; 
    public void showGUI() 
    { 
     setTitle("Close me"); 
     getContentPane().add(new JLabel("Close me"),BorderLayout.NORTH); 
     addWindowListener(new WindowAdapter() 
     { 
      @Override 
      public void windowClosing(WindowEvent evt) 
      { 
       callMeBeforeExit(); 
       System.exit(0);//Don't write this line if you don't want your program to exit 
      } 
     }); 
     setSize(200,200); 
     setVisible(true); 
    } 
    private void callMeBeforeExit() 
    { 
     Random random = new Random(); 
     int i = random.nextInt(strings.length - 1);//Defines the Range of numbers to be chosen randomly. 
     System.out.println(strings[i]); 
    } 
    public static void main(String st[]) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       WorkBeforeClose wbc = new WorkBeforeClose(); 
       wbc.showGUI(); 
      } 
     }); 
    } 
} 
+0

另一個問題是,我想隨意採摘一個字符串,然後放入的System.out.println?我該如何做到這一點,謝謝 – 2013-03-13 17:29:49

+0

@JoshuaBaron你有'字符串'存儲在'數組'字符串'? – 2013-03-13 17:31:18

+0

不,我不只是在正常的字符串中加入 – 2013-03-13 17:40:06