有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么主方法不运行?

对Java中的公共静态void main方法有点困惑,希望有人能提供帮助。我有两节课

    public class theGame {
        public static void main(String[] args) {
            lineTest gameBoard = new lineTest();
    }

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);
    }

    public static void main(String[] args) {
        lineTest points = new lineTest();
        JFrame frame = new JFrame("Points");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(points);
        frame.setSize(250, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

不幸的是,我的程序没有划定界限。我试图弄明白为什么lineTest类中的main方法不起作用

虽然我可以通过将main方法更改为其他方法(例如“go”,然后从“theGame”类运行该方法)来实现,但我很好奇lineTest类中的main方法为什么不起作用


共 (3) 个答案

  1. # 1 楼答案

    我从下面开始。看起来您可能想花一些时间学习更基础的java教程或课程,以掌握最新的java基础知识

    在下面的代码中,类theGame有一个程序的主条目。JVM将在程序开始时调用main方法。从那里,它将执行您给出的指令。因此,在大多数情况下,两种主要方法在单个项目中没有意义。此规则的例外情况是,如果您希望在同一程序中有两个单独的应用程序入口点(例如,使用相同逻辑但控制方式不同的命令行应用程序和GUI应用程序)

    因此,使用下面的代码,在启动此应用程序的JVM时,必须将TheGame类指定为主入口点

    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();
        }    
    }
    

    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);
        }
    }
    
  2. # 2 楼答案

    当java应用程序被执行时,它是通过调用一个特定类上的main方法来执行的。此主方法将是选择要执行的类上的任何主方法

    在本例中,您选择在类theGame上执行main方法

    当在应用程序中构造另一个类时,该类的构造函数将自动执行,但该类上的主方法不会自动执行

  3. # 3 楼答案

    应用程序有一个入口点,该入口点是执行的单个主方法。如果您的入口点是theGame类,则只执行该类的主方法(除非手动执行其他类的主方法)

    创建lineTest类的实例不会导致执行其主方法