The difference I see (works on JDK 1.7):
setVisible(false) calls componentHidden but not windowClosed (the API only declares to dispose() , so it's ok even if it annoys me)
but
dispose() calls windowClosed but not componentHidden
Short Run Code Code (MCVE):
public class JDialogTest extends JDialog { private static final long serialVersionUID = 1L; public JDialogTest(JFrame owner){ super(owner,ModalityType.APPLICATION_MODAL); init(); } private void init() { this.getContentPane().setLayout(new GridLayout(1,2)); JButton btnVisible = new JButton("Set visible false"); btnVisible.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JDialogTest.this.setVisible(false); } }); JButton btnDispose = new JButton("Dispose"); btnDispose.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JDialogTest.this.dispose(); } }); this.getContentPane().add(btnVisible); this.getContentPane().add(btnDispose); this.pack(); } public static void main(String[] args) {
NOTE: There is JDialog in the example, but I see the same behavior in JFrame to check, just connect listeners to fakeFrame and add similar buttons. (avoided in MVCE to keep it M inimal)).
I reviewed this post:
JDialog setVisible (false) vs dispose ()
- The answers seem to make no difference, use
dispose() ...
API DOCUMENTATION:
Window.setVisible (boolean b) , Window.dispose () , ComponentListener.componentHidden (ComponentEvent e) , WindowListener.windowClosed (WindowEvent e)
Why is it important to me . Naturally, out of curiosity, but also because I use the buttons to close the window (calling dispose() ), and the interface can also be closed by closing the top / right window icon and alt + F4 (calling setVisible(false) !?). Therefore, none of the above listener can be used. Only the HierarchyListener will catch them both, and this seems like an intuitive counter.
EDIT: The question is considered as "why is this so"? What is the purpose? "I expected dispose() call both! I can't find any hints in the API documentation, why not.