access reference without knowing reference name

48 Views Asked by At

I have a class named NetPosition which has a JFrame and that JFrame contains a button which if clicked makes object of another class called BuyScreen and opens another JFrame.THe problem is when the parent frame is closing i want all the BuyScreen frames to be closed.Something like this

frame.addWindowListener(new WindowListener() {

    @Override
    public void windowOpened(WindowEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowIconified(WindowEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowDeiconified(WindowEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowDeactivated(WindowEvent e) {
        // TODO Auto-generated method stub

    }

    @Override

    /*Closing all the buy screens and sells screens of marketwatch before market watch screen is closed*/
    public void windowClosing(WindowEvent e) {
        // TODO Auto-generated method stub
        if(BuySellNetPosition.countBuySellNetPosition!=0)
        {
            BuySellNetPosition.frame
        }

    }

    @Override
    public void windowClosed(WindowEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowActivated(WindowEvent e) {
        // TODO Auto-generated method stub

    }
});

The child frame is not static.I can have several BuyScreen frames opened at the same time.Is it possible to close all frames of a particular class without knowing the names of references to that class. Previously i made an array of BuyScreen objects to handle this problem.But i am wondering if there is another way.

2

There are 2 best solutions below

0
On BEST ANSWER

Whenever you create a new BuyScreen, you should be adding it as a listener to your main frame that you want to respond to. That way, whenever the main frame closes, it will notify all the BuyScreen frames that you want to close.

You don't need to maintain a collection of the frames yourself. The addWindowListener() call will do that for you.

Your windowClosing() implementation within the BuyScreen just needs to check that it's the main window that's the source of the event, and then close itself.

2
On

You have to store all your BuyScreens in some sort of collection eg. LinkedList<ButScreen>. You will be able to iterate over that collection and close alle related BuyScreens.

Or use JDialogs with parent set as your BuyScreens. They will all close automaticly when the parent frame/dialog will be closed.