Search code examples
javaswingclassjframeprogram-entry-point

How do I use a JFrame class as main class?


I'm trying to build a calculator.

I've developed the interface using the Swing plug-in (containers and controls), but when I try to run my program it says the package needs a main class.

Already tried to create a main class and call the Calc() JFrame class, but it didn't work.

Take a look at the code:

public class Calc extends javax.swing.JPanel {
    public Calc() {
        initComponents();
    }
}

Solution

  • You need a main() method to execute your class.

    Take a look at the FrameDemo example code found in the Swing tutorial on How to Make Frames for a basic example to get you started.

    /* FrameDemo.java requires no other files. */
    public class FrameDemo {
    
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("FrameDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        JLabel emptyLabel = new JLabel("");
        emptyLabel.setPreferredSize(new Dimension(175, 100));
        frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
    
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
    
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
      }
    }