简体   繁体   中英

unwanted multiple instances java

New question. After adjusting my program according to steps in my previous question: How to access already running instance of a class without creating an actual object

I have came up new weird problem. I am passing a reference of I to G via constructor then use that reference to manipulate I from G. I have mapped that function to "back button". Problem: if I hit back button and do and adjust my I frame then click finish button which hides I interface and sets G frame to visible. I have another button that simply creates new clear instance of I, upon pressing that, I get a flood of I instances open up (directly proportional to how many times I have pressed back button). After extensive debugging I am still puzzled... Maybe its an issue with me creating too many threads... I dont know.. here some code snippets:

G Constructor:

 public GUI(Intro i) {
    this.intro = i;
    make();
    layout();
    layout2();
    layout3();
    invalid();
    setEnable();
}

Back button code:

private class BackToSetUp implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent arg0) {
        intro.frame.setVisible(true);
        frame.dispose();
    }

}

Reset button code:

private class ResetProgram implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent arg0) {
        frame.dispose();
        frame2.dispose();
        frame3.dispose();
        frame4.dispose();
        Runnable runnable = new Runnable() {
            public void run() {

                intro = new Intro(); 
                intro.setVisible(true);

            }
        };
        EventQueue.invokeLater(runnable);


    }

}

Finish button code:

class Done implements ActionListener {
    GUI g = new GUI();
    @Override
    public void actionPerformed(ActionEvent e) {

        for (int i = 0; i < 9; i++) {
            System.out.println(array[i]);
        }

        g.setArray(array);
        System.out.println(array);
        setText();
        frame.setVisible(false);
        g.setVisible(true);
        g.setVisible2(false);
        //if (g.clear.isSelected()) {
        //  frame.setVisible(true);
        //}
    }

Setting previous G instance to null solves the issue because garbage collector disposes of it thus there is only one instance of each class running at a time. SOLVED

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM