javaswingnetbeansjframegui-builder

NetBeans inserts main() method in every added frame


When adding new class extending JFrame (or java.awt.Frame) the class is added with main() method inside like this:

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewFrame5().setVisible(true);
        }
    });
}

Every JFrame class has its own main method and I guess all classes starts simultaneously.

How do I add frames without main methods?


Solution

  • Firstly, see The Use of Multiple JFrames, Good/Bad Practice?. Generally, recommended not to do it. See accepted answer for other possibilities (for example a JDialog)

    As for your main concern, there's no way around netbeans creating the main method for top level containers like JFrame and JDialog. The logic seems right in the case of JFrame, as an application should only have one JFrame as the main top-level container for the application, but I'm not sure the logic behind the JDialog having a main method (as the dialog is usually run in the same JVM as the main JFrame). The only thing I can think is that the JDialog is created with a main for development purpopsed, if you want to test the dialog in stand-alone mode. But ultimately, you should delete the main method of the JDialog should you choose to use one.

    Going back to the first point about multiple JFrames, other options I might recommend


    An aside, if you are a beginner, I strongly suggest you put aside the builder tool and learn to hand code first. There may be many tutorials teaching you how to use the builder tool, but they may miss out on important concept in the swing architecture and swing in general. IMO this will greatly affect your understanding of how and why things work with the builder, causing a lot a headache when trying to debug. Keep Creating a GUI With JFC/Swing, the official tutorial handy and go through it.