java - Detect when user closes floating toolbar frame -
is possible capture event when user tries close floating toolbar window in swing? in advance.
there's awesomely simple solution, why use that?
the best come (without extending out own tool bar) add ancestorlistener
toolbar , monitor it's events.
the problem have approach, though, need know main frame attached to, may not convenient.
import java.awt.borderlayout; import java.awt.eventqueue; import java.awt.event.componentevent; import java.awt.event.componentlistener; import java.awt.event.containerevent; import java.awt.event.containerlistener; import java.awt.event.hierarchyevent; import java.awt.event.hierarchylistener; import java.beans.propertychangeevent; import java.beans.propertychangelistener; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jtoolbar; import javax.swing.swingutilities; import javax.swing.uimanager; import javax.swing.unsupportedlookandfeelexception; import javax.swing.event.ancestorevent; import javax.swing.event.ancestorlistener; public class testfloatingtoolbar { public static void main(string[] args) { new testfloatingtoolbar(); } public testfloatingtoolbar() { eventqueue.invokelater(new runnable() { @override public void run() { try { uimanager.setlookandfeel(uimanager.getsystemlookandfeelclassname()); } catch (classnotfoundexception | instantiationexception | illegalaccessexception | unsupportedlookandfeelexception ex) { } final jframe frame = new jframe("test"); final jtoolbar tb = new jtoolbar(); tb.add(new jbutton("pop")); tb.setfloatable(true); tb.addancestorlistener(new ancestorlistener() { @override public void ancestoradded(ancestorevent event) { tell(); if (swingutilities.getwindowancestor(tb).equals(frame)) { system.out.println("...in main frame"); } else { system.out.println("...maybe floating"); } } @override public void ancestorremoved(ancestorevent event) { tell(); if (swingutilities.getwindowancestor(tb).equals(frame)) { system.out.println("...in main frame"); } else { system.out.println("...maybe floating"); } } @override public void ancestormoved(ancestorevent event) { } }); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setlayout(new borderlayout()); frame.add(tb, borderlayout.north); frame.pack(); frame.setlocationrelativeto(null); frame.setvisible(true); } }); } public void tell() { exception exp = new exception(); stacktraceelement[] stacktrace = exp.getstacktrace(); system.out.println(stacktrace[1].getmethodname()); } }