title: How to run some code when a window (jframe) loads in java?
body: <p>I have made a program in Java that has two windows (JFrames):</p>
  
  <p>a) The Log-in Window,</p>
  
  <p>b) The Main Window.</p>
  
  <p>The "Log-in Window" calls the "Main Window" and then closes.</p>
  
  <p>How can I run some code when the "Main Window" is loading (run some code only once, when the "Main Window" frame opens for the first time)?</p>
  
  <p>I try the below code in the <code>main()</code> method of the "Main Window" but it doesn't work...</p>
  
  <p>Code in Main-Window.java file:</p>
  
  <pre><code>public static void main(String[] args) {
  
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        try {
  
          final Main_Window frame = new Main_Window();            
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
  
          frame.addWindowListener(new WindowAdapter() {
            public void windowOpened(WindowEvent e) {
              runSomeCode();
            }
          });
  
        } catch (Exception e) {
          e.printStackTrace();
        }
  
      }
  
    });
  
  }
  </code></pre>
  
  <p><em>The <code>runSomeCode();</code> never executes...</em></p>
  
  <p>The way that the "Log-in Window" closes and calls the "Main Window" is this:</p>
  
  <p>Code in Log-in-Window.java file:</p>
  
  <pre><code>Main_Window mw = new Main_Window();
  mw.setLocationRelativeTo(null);
  mw.setVisible(true);
  
  WindowEvent winCloseEvent = new WindowEvent(this,WindowEvent.WINDOW_CLOSING);
  Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winCloseEvent);
  </code></pre>