Search code examples
javaswingmodal-dialogjframevisible

How to add a WindowListener to an external event


This is my code I have developed. This is the main program which holds and executes each external JFrame for my Game. chooseGender is an external program which is nothing but a JFrame and its components.

My goal for this is when chooseGender executes, it has 2 buttons for options (male, female) when the user picks one, an actionListener would set the frame to setVisible(false) and then have a WindowClosing event open the next JFrame, (chooseRace). This would happen for several more frames but these 2 are for learning purposes. I appreciate the help in advance. :)

So my question is, how would I go about adding a WindowListener to chooseGender in this program so I can close it and open the next one?

package javagame;

import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;

public class Main implements WindowListener {


    public static void main(String[] args) {

             EventQueue.invokeLater(new Runnable() {

            public void run() {
                new chooseGender().setVisible(true);
            }
        });

          EventQueue.invokeLater(new Runnable() {

            public void run() {
                new chooseRace().setVisible(false);
            }
        }); 
    }

Solution

  • An easy way to implement this may be just using modal JDialogs.

    The code would be similar to the following:

    main {
    
        new chooseGender().setVisible(true);
        new chooseRace().setVisible(true);
        new chooseAge...
    
    }
    

    You would want to implement a WidowListener similar to the following:

    public class OpenNewWindowWindowListener extends WindowAdapter {
        public void windowClosing(WindowEvent e){
            // in here open the next window.
        }
    }
    

    And add that window listener to the correct frame:

    // In the constructor for the JFrame
    addWindowListener(new OpenNewWindowListener());
    

    And, each of those classes would extend JDialog and, in their constructors use setModal(true).