简体   繁体   中英

Why this function for JFrame is executed twice?

Introduction

I'm learning how to present GUIs for user 'friendly' input. I will reference below some web pages for those who are interested in the matter.

Code

public class TestGUI{

    private JFrame mainFrame;
    private JLabel headerLabel;
    private JLabel statusLabel;
    private JPanel controlPanel;

    public TestGUI()
    {
        prepareGUI();
    }

    private void prepareGUI()
    {
        mainFrame = new JFrame("TestGUI"); //Header name
        mainFrame.setSize(420, 320); //Size of the frame
        mainFrame.setLayout(new GridLayout(3, 1)); //??

       mainFrame.addWindowListener(new WindowAdapter() //Waits for an user event
       {
         //When the frame is closes, the program does too.
         @Override
         public void windowClosing(WindowEvent windowEvent)
         {
            System.exit(0); //Exit program
         }        
      });

       mainFrame.setVisible(true);//GUI is visible
    }

    public static void main(String[] args) {

        TestGUI test = new TestGUI(); //constructor
        test.prepareGUI(); //Call the method
    }

}

Problem

While running the code I saw that 2 identical frames pop up. I went to debug it and saw that it is executed twice when I call the method!

Why is that?

I only called it once with testGUI.prepareGUI(); in the main function.

Webpages for learning basic GUI in Java

JavaFX

GUI Programming with AWT

You call prepareGUI() in the constructor as well.

public TestGUI()
{
    prepareGUI();
}

When you call new TestGUI() , this constructor gets called and so does the function.

You are calling prepareGui twice

Once here

  public TestGUI()
    {
        prepareGUI();
    }

and once here

    TestGUI test = new TestGUI(); //constructor
    test.prepareGUI(); //Call the method

so first block is executed on new TestGUI() call

You are calling the prepareGui() method twice. One in your constructor and once on your created object (in the main method)

The issue is that constructor (that is TestGUI()) you are already calling prepareGUI(). so just omit the other call to prepareGUI(), which is test.prepareGUI().

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