Why doesn't the main method run?

后端 未结 3 1055

A bit confused about the public static void main method in Java and was hoping someone could help. I have two classes

    public class theGame {
        public s         


        
相关标签:
3条回答
  • 2021-01-26 16:07

    When a java application is executed, it is executed by invoking the main method on one particular class. This main method will be whichever main method is on the class that was selected to executed.

    In your case, you are selecting to execute the main method on the class theGame.

    When another class is constructed in the application, the constructor of that class is automatically executed, but the main method on that class is not automatically executed.

    0 讨论(0)
  • 2021-01-26 16:24

    I've made a start below. It looks like you might want to invest some time in following a more basic java tutorial or course to get your basic java knowledge up to speed.

    What happens in the code below is that the class theGame has a main entry for the program. The JVM will invoke the main method at the start of your program. From there, it will execute the instructions you give. So most of the times, two main methods do not make sense in a single project. Exception to this rule is if you want to have two separate application entry points two the same program (for instance a command-line application and a GUI application that use the same logic but are controlled differently).

    So with the code below, you will have to specify the TheGame class as a main entry point when starting your JVM for this application.

    public class TheGame {
        private final LineTest theBoard;
        public TheGame() {
            theBoard = new LineTest();
        }
    
        public void run() {
            JFrame frame = new JFrame("Points");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(theBoard);
            frame.setSize(250, 200);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        /**
         * Main entry for the program. Called by JRE.
         */
        public static void main(String[] args) {
            TheGame instance = new TheGame();
            instance.run();
        }    
    }
    

    and

    public class LineTest extends JPanel {
    
    public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setColor(Color.red);
            g2d.drawLine(100, 100, 100, 200);
        }
    }
    
    0 讨论(0)
  • 2021-01-26 16:26

    Your application has one entry point, and that entry point is the single main method that gets executed. If your entry point is the theGame class, only the main method of that class will be executed (unless you manually execute main methods of other classes).

    Creating an instance of lineTest class doesn't cause its main method to be executed.

    0 讨论(0)
提交回复
热议问题