Setti setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOS E) e poi registri un WindowListener sulla finestra.