【问题标题】:Why doesn't the main method run?为什么 main 方法不运行?
【发布时间】:2015-09-19 20:30:53
【问题描述】:

对 Java 中的 public static 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 方法不感兴趣'没用。

【问题讨论】:

  • 您要执行哪个主要任务?为什么你有两种主要方法?

标签: java main


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我已经在下面开始了。看来您可能想花一些时间来学习更基本的 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);
        }
    }
    

    【讨论】:

      【解决方案3】:

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

      在您的情况下,您选择在 theGame 类上执行 main 方法。

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

      【讨论】:

        猜你喜欢
        • 2023-03-16
        • 2014-12-18
        • 2021-07-25
        • 1970-01-01
        • 2011-02-22
        • 2012-12-03
        • 1970-01-01
        • 2012-05-06
        • 1970-01-01
        相关资源
        最近更新 更多