Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For this answer I'm making a minor assumption that the Nullpointer is not being thrown at the line that you mentioned, but rather when you attempt to add the WindowListener to the parentFrame. This is most likely because you're calling </p> <pre><code>JFrame parentFrame = (JFrame) SwingUtilities.getWindowAncestor(this); </code></pre> <p>before the JPanel has been added to the JFrame hierarchy. </p> <p>Here's a rought code sample on how you could work around this. The thought it to wait for the panel to be notified that it has been attached to the JFrame somewhere in its hierarchy.</p> <pre><code>package test; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class HierarchyTest extends JPanel { protected static void loadApp() { HierarchyTest test = new HierarchyTest(); JFrame frame = new JFrame(); frame.add(test); frame.setSize(200, 200); frame.setVisible(true); } /** * @param args */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { loadApp(); } }); } public HierarchyTest() { this.addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { // This can be optimized by checking the right flags, but I leave that up to you to look into boolean connected = setupListenersWhenConnected(); if (connected) { HierarchyTest.this.removeHierarchyListener(this); } } }); } protected boolean setupListenersWhenConnected() { JFrame parentFrame = (JFrame) SwingUtilities.getWindowAncestor(this); if (parentFrame == null) { return false; } parentFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // Implementation here System.out.println("This window is closing!"); } }); return true; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload